栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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:DevFoldercodehellohello-bat-is-not-multi-threadtarget>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:DevFoldercodehellohello-bat-is-not-multi-threadtarget>echo RunningscriptHere
RunningscriptHere

D:DevFoldercodehellohello-bat-is-not-multi-threadtarget>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:DevFoldercodehellohello-bat-is-not-multi-threadtarget>pause
请按任意键继续. . .
补充

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/345176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号