多线程顺序执行

对于多线程的顺序执行有很多种实现方式 这里记录三种

 

还可以使用锁的形式 比如volatile关键字+synchronized/ReentrantLock

或者condition对象用来await(阻塞)和signal(唤醒)指定的线程

当然还有使用single线程池来实现本文只记录使用以下工具类来实现

CountDownLatch/Semaphore/BlockingQueue

方式一:使用CountDownLatch工具进行实现  

public static void main(String[] args) {
CountDownLatch countDownLatch12=new CountDownLatch(1);
CountDownLatch countDownLatch23=new CountDownLatch(1);
Thread threada=new Thread(()->{
System.out.println(Thread.currentThread().getName()+"执行");
countDownLatch12.countDown();
},"threada");
Thread threadb=new Thread(()->{
try {
countDownLatch12.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行");
countDownLatch23.countDown();
},"threadb");
Thread threadc=new Thread(()->{
try {
countDownLatch23.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行");
},"threadc");
threada.start();
threadb.start();
threadc.start();
}
方式二:使用Semaphore工具进行实现
public static void main(String[] args) {
Semaphore semaphore12=new Semaphore(0);
Semaphore semaphore23=new Semaphore(0);
Thread threada = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"执行");
semaphore12.release();
}, "threada");
Thread threadb = new Thread(() -> {
try {
semaphore12.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行");
semaphore23.release();
}, "threadb");
Thread threadc = new Thread(() -> {
try {
semaphore23.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行");
}, "threadc");
threada.start();
threadb.start();
threadc.start();
}

方式三:使用BlockingQueue阻塞队列进行实现
public static void main(String[] args){
BlockingQueue<String> blockingQueue12, blockingQueue23;
blockingQueue12=new SynchronousQueue<>();
blockingQueue23=new SynchronousQueue<>();

Thread threada=new Thread(()->{
System.out.println(Thread.currentThread().getName());
try {
blockingQueue12.put("stop");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"threada");
Thread threadb=new Thread(()->{
try {
blockingQueue12.take();
System.out.println(Thread.currentThread().getName());
blockingQueue23.put("stop");
} catch (InterruptedException e) {
e.printStackTrace();
}

},"threadb");
Thread threadc=new Thread(()->{

try {
blockingQueue23.take();
System.out.println(Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
},"threadc");
threada.start();
threadb.start();
threadc.start();
}

 
 

 

 

 
posted @ 2021-01-25 17:27  java程序猴  阅读(346)  评论(0编辑  收藏  举报