package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
public class Command {
public static void main(String[] args) throws Exception {
ResourceBundle resource = ResourceBundle.getBundle("config");
Thread gitThread = new gitStartThread(resource);
gitThread.start();
gitThread.join();
System.out.println("haha");
}
static class gitStartThread extends Thread {
ResourceBundle resource;
public gitStartThread(ResourceBundle resource) {
this.resource = resource;
this.setDaemon(true);
}
@Override
public void run() {
Process process;
try {
process = Runtime.getRuntime().exec(resource.getString("cmd"));
System.out.println("写入cmd成功");
PrintWriter writer = new PrintWriter(process.getOutputStream());
writer.println(resource.getString("GITCMD"));
writer.flush();
System.out.println("写入GIT成功,开始拉取...");
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("gitstart运行异常");
e.printStackTrace();
} finally {
}
}
}
}
如上这里线程并不会被运行,而是主线程一下子运行完了,子线程没被执行
注:
resource.getString("cmd")拿到的字符是cmd
resource.getString("GITCMD")拿到的字符是git clone -b wlnsss_dev https://gitee.com/Wx
上面拉取git的字符乱写的,反正程序的最终作用就是
这是一个通过Java调用cmd拉取git到本地的程序,如果在join方法前加入线程睡眠似乎会正常执行,请各位大佬讲解下这是为什么,谢谢啦
老哥,你这个不是线程问题,而是进程问题。
你的程序逻辑是这样的:
**Process Main -> Thread Main -> Thread gitThread -> ChildProcess cmd **
你只注意到主进程中的主线程需要等待子线程执行完成,却没有注意到主进程需要等待子进程执行完成。
所以,你需要在gitThread中等待cmd执行的子进程git完成。
http://bjyzxxds.iteye.com/blog/444181
public static void main(String[] args) throws Exception {
ResourceBundle resource = ResourceBundle.getBundle("config");
Thread gitThread = new gitStartThread(resource);
gitThread.start();
gitThread.join();
System.out.println("haha");
}
static class gitStartThread extends Thread {
ResourceBundle resource;
public gitStartThread(ResourceBundle resource) {
this.resource = resource;
this.setDaemon(true);
}
@Override
public void run() {
Process process;
try {
process = Runtime.getRuntime().exec(resource.getString("cmd"));
System.out.println("写入cmd成功");
PrintWriter writer = new PrintWriter(process.getOutputStream());
// writer.println(resource.getString("GITCMD"));
// writer.flush();
System.out.println("写入GIT成功,开始拉取...");
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("gitstart运行异常");
e.printStackTrace();
} finally {
}
}
}
这样的时候是没有问题的
td:focus {
background-color: yellow; // 颜色可自定义
}
https://blog.csdn.net/love_1054056499_love/article/details/78252884
this.setDaemon(true);
gitThread.join();会失效
线程setDaemon(true)就是将当前进程变成后台进程。
如果对某个线程对象在启动(调用start方法)之前调用了setDaemon(true)方法,这个线程就变成了后台线程.对java程序来说,只要还有一个前台线程在运行,这个进程就不会结束,如果一个进程中只有后台线程运行,这个进程会结束.
你的jdk是哪个版本,我本地执行了一下,可以执行,setDaemon(true)设置为守护线程,
优先级最低,一般情况下是最后执行,但是看到你的程序有join()方法,所以主线程会等待这个守护线程执行完以后,才会执行