在bash线程? [英] Threads in bash?

查看:98
本文介绍了在bash线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在bash脚本中使用线程.我在Java中有一个驱动程序类,试图同时运行多个实例.我知道做到这一点的唯一方法是在bash中创建线程,但是我不确定那是否有可能.任何帮助将不胜感激

Is it possible to use threads in bash scripts. I have a driver class in java that i'm trying to run multiple instances of at the same time. The only way i know to do this is make threads in bash, but i'm not sure if thats even possible. Any help would be appreciated

推荐答案

Bash本身不支持线程,但是您可以在后台启动多个Java进程,例如:

Bash doesn't support threading per se, but you could launch multiple java processes in the background, like:

java myprog &
java myprog &
java myprog &

除了拥有线程管理实用程序的Python或Ruby之外,您还可以等待其他任何内容,并等待它们完成并收集输出/退出状态等.

Anything more than that you might look into Python or Ruby, which have thread management utilities, you could wait for each one to finish and collect output/exit status, etc.

编辑:借鉴@CédricJulien的建议使用wait,这是一个更详尽的示例.给出以下MyProg.java程序:

Edit: Borrowing the suggestion from @CédricJulien to use wait, here's a more thorough example. Given this MyProg.java program:

public class MyProg {
    public static void main(String[] args) {
        System.exit(Integer.parseInt(args[0]));
    }
}

您可以编写以下bash-threads.sh脚本来并行启动它的多个实例:

you could write the following bash-threads.sh script to launch multiple instances of it in parallel:

#!/bin/bash
set -o errexit

java MyProg 1 &
pid1=$!
java MyProg 0 &
pid2=$!
java MyProg 2 &
pid3=$!

wait $pid1 && echo "pid1 exited normally" || echo "pid1 exited abnormally with status $?"
wait $pid2 && echo "pid2 exited normally" || echo "pid2 exited abnormally with status $?"
wait $pid3 && echo "pid3 exited normally" || echo "pid3 exited abnormally with status $?"

其输出是:

pid1 exited abnormally with status 1
pid2 exited normally
pid3 exited abnormally with status 2

这篇关于在bash线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆