当前位置:   article > 正文

有三个线程,怎么让他们按顺序执行_c++多线程使用三个线程顺序执行实例

c++多线程使用三个线程顺序执行实例

第一种:

        用Thread.join() 方法 确定该线程执行完毕

第二种

线程池   newSingleThreadExecutor  这个线程处理完一个任务后接着处理下一个任务

 

具体代码:

第一种:

package com.cun;


public class JoinTest {


public static void main(String[] args) {
final Thread join1 = new Thread(new Runnable() {


@Override
public void run() {
  System.out.println("join1");  
}  
}, "T1");

final Thread join2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join2");  
try {
join1.join();//确定join1执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
}  
}, "T2");
final Thread join3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join3");  
try {
join2.join();//确定join2执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
}  
}, "T3");
join1.start();
join2.start();
join3.start();
}
}



第二种:

package com.cun;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class JoinTest1 {


public static void main(String[] args) {
final Thread join1 = new Thread(new Runnable() {


@Override
public void run() {
  System.out.println("join1");  
}  
}, "T1");

final Thread join2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join2");  
}  
}, "T2");
final Thread join3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("join3");  
}  
}, "T3");
   ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(join1);
        executor.submit(join2);
        executor.submit(join3);
        executor.shutdown();
}
}




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/197861
推荐阅读
相关标签
  

闽ICP备14008679号