多线程的执行顺序,在下进来了解了一点
先来原来的没有排序的线程是怎么样的
public class App {staticThread thread1 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread1");
}
});
staticThread thread2 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2");
}
});
staticThread thread3 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
//join:让主线程等待子线程结束以后才能继续运行
System.out.println("Hello World");
thread1.start();
thread2.start();
thread3.start();
}
}
结果是
![个人心得|如何控制多线程的执行顺序](https://img.it610.com/image/info8/4d76c929527a4b94907613030a4518f1.jpg)
文章图片
然后第一种是join:
public class App {staticThread thread1 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread1");
}
});
staticThread thread2 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2");
}
});
staticThread thread3 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
//join:让主线程等待子线程结束以后才能继续运行
System.out.println("Hello World");
thread1.start();
thread1.join();
thread2.start();
thread1.join();
thread3.start();
}}
然后结果
![个人心得|如何控制多线程的执行顺序](https://img.it610.com/image/info8/0306066a765c4a8e94ee1d56c248a497.jpg)
文章图片
第二种是用了
ExecutorService executorService = Executors.newSingleThreadExecutor();
public class App {staticThread thread1 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread1");
}
});
staticThread thread2 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2");
}
});
staticThread thread3 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
//join:让主线程等待子线程结束以后才能继续运行
/*System.out.println("Hello World");
thread1.start();
thread1.join();
thread2.start();
thread1.join();
thread3.start();
*/
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);
executorService.shutdown();
}}
【个人心得|如何控制多线程的执行顺序】
推荐阅读
- android|android https 双向认证--高级
- android|android 使用crt/cer/pem格式的公钥证书
- 个人心得|TFlow的超时检测,delay操作
- 随笔记录|最新邮箱匹配正则(邮箱前缀可包含"_")
- 前端|兼容IE8及其以下的DOM元素方法——低版本浏览器也能用class取DOM