shell或bat脚本是不是顺序执行,是多线程吗,会不等待java执行结果吗

背景

研究bat/sh脚本是否是多线程执行的(或者说对java的jar进行调用是否调用后就立即返回,还是需要等到执行完毕再执行下面的脚本)

动手实验

Test.java类,代码如下

public class Test {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("------- main enter ------------");
        if (args == null || args.length == 0) {
            throw new RuntimeException("Please input param (args[0],unit is second)");
        }
        int seconds = Integer.parseInt(args[0]);
        for (int i = 1; i <= seconds; i++) {
            System.out.println("---- sleeping: " + (i + " / " + seconds));
            Thread.sleep(1000);
        }
        System.out.println("------- main exit ------------");
    }
}

脚本,保存为 test.bat 或者 test.sh,在windows双击打开运行或者linux的环境中执行 ./test.sh。脚本如下:

java -cp hello-bat-is-not-multi-thread-1.0-SNAPSHOT.jar com.wyf.test.Test 10
echo RunningScriptHere
java -cp hello-bat-is-not-multi-thread-1.0-SNAPSHOT.jar com.wyf.test.Test 2
pause

linux里没有pause,不过也不会报错,是否去掉没有关系

我们要观察的点是,RunningScriptHere 是不是在main方法执行完毕后才打印出来。可以多试几遍。

如果是,那说明脚本会等待第一行脚本运行完毕后才继续。

结论

测试结果:是的,无论在win还是linux,都是这样。

  • linux 结果
[root@iZuf7g5sz3emax84qa7ta6a test]# ./test.sh 
------- main enter ------------
---- sleeping: 1 / 10
---- sleeping: 2 / 10
---- sleeping: 3 / 10
---- sleeping: 4 / 10
---- sleeping: 5 / 10
---- sleeping: 6 / 10
---- sleeping: 7 / 10
---- sleeping: 8 / 10
---- sleeping: 9 / 10
---- sleeping: 10 / 10
------- main exit ------------
RunningScriptHere
------- main enter ------------
---- sleeping: 1 / 2
---- sleeping: 2 / 2
------- main exit ------------
./test.sh: line 4: pause: command not found
  • Windows 结果
D:\DevFolder\code\hello\hello-bat-is-not-multi-thread\target>java -cp hello-bat-is-not-multi-thread-1.0-SNAPSHOT.jar com.wyf.test.Test 10
------- main enter ------------
---- sleeping: 1 / 10
---- sleeping: 2 / 10
---- sleeping: 3 / 10
---- sleeping: 4 / 10
---- sleeping: 5 / 10
---- sleeping: 6 / 10
---- sleeping: 7 / 10
---- sleeping: 8 / 10
---- sleeping: 9 / 10
---- sleeping: 10 / 10
------- main exit ------------

D:\DevFolder\code\hello\hello-bat-is-not-multi-thread\target>echo RunningScriptHere
RunningScriptHere

D:\DevFolder\code\hello\hello-bat-is-not-multi-thread\target>java -cp hello-bat-is-not-multi-thread-1.0-SNAPSHOT.jar com.wyf.test.Test 2
------- main enter ------------
---- sleeping: 1 / 2
---- sleeping: 2 / 2
------- main exit ------------

D:\DevFolder\code\hello\hello-bat-is-not-multi-thread\target>pause
请按任意键继续. . .

补充

上述的研究背景是什么?上述是为了研究接口的限流,配置了1秒内只能调用1次否则就触发限流,由于手速没这么快,想用脚本来替代(不想jmeter或者其他方式),然后就研究了这个,发现这种做法没办法满足,假设接口耗时超过1秒,根本就不可能触发限流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值