1.题目
Java实现两个线程依次交替运行
2.代码
1 import java.util.concurrent.TimeUnit; 2 import java.util.concurrent.locks.Condition; 3 import java.util.concurrent.locks.ReentrantLock; 4 5 /** 6 * @title 两个线程依次交替执行 7 * @description 假定两个线程分别为红灯、绿灯,执行的期待结果为:红-绿-红-绿-红-绿... 8 * @author ocaicai@yeah.net 9 * @since 2013-8-17 下午12:51:1110 */11 public class AlternateRun2 implements Runnable {12 13 private int tnum = 1;// 线程编号,Thread Number14 15 private ReentrantLock lock = new ReentrantLock();16 17 private Condition redCon = lock.newCondition();18 private Condition greenCon = lock.newCondition();19 20 public static void main(String[] args) {21 new AlternateRun2().run();22 }23 24 @Override25 public void run() {26 new Thread(new RedThread(), "red light").start();27 new Thread(new GreenThread(), "green light").start();28 }29 30 class RedThread implements Runnable {31 32 @Override33 public void run() {34 while (true) {35 try {36 lock.lock();37 while (tnum != 1) { // 判断是否该自己执行了[采用while不是if是为了防止死锁]38 redCon.await();39 }40 System.out.println(Thread.currentThread().getName()+ " is flashing...");41 42 TimeUnit.SECONDS.sleep(1);// 停留时间,便于从控制台观看43 44 tnum = 2;45 greenCon.signal();46 47 } catch (InterruptedException e) {48 e.printStackTrace();49 } finally {50 lock.unlock();51 }52 }53 }54 }55 56 class GreenThread implements Runnable {57 58 @Override59 public void run() {60 61 while (true) {62 try {63 lock.lock();64 while (tnum != 2) {65 greenCon.await();66 }67 System.out.println(Thread.currentThread().getName()+ " is flashing...");68 69 TimeUnit.SECONDS.sleep(1);// 停留时间,便于从控制台观看70 71 tnum = 1;72 redCon.signal();73 74 } catch (InterruptedException e) {75 e.printStackTrace();76 } finally {77 lock.unlock();78 }79 }80 }81 82 }83 84 }
3.执行结果
red light is flashing...
green light is flashing...red light is flashing...green light is flashing...red light is flashing...green light is flashing...red light is flashing...
green light is flashing...red light is flashing...green light is flashing...red light is flashing...green light is flashing...red light is flashing...
green light is flashing...red light is flashing...green light is flashing...red light is flashing...green light is flashing...4.参考
1 /** 2 * ref http://coolxing.iteye.com/blog/1236696 3 * desc: java并发编程--一道经典多线程题的 4 * 启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 5 * 然后是线程2打印6,7,8,9,10, 6 * 然后是线程3打印11,12,13,14,15. 7 * 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为: 8 * 9 * 线程1: 110 * 线程1: 211 * 线程1: 312 * 线程1: 413 * 线程1: 514 * 15 * 线程2: 616 * 线程2: 717 * 线程2: 818 * 线程2: 919 * 线程2: 1020 * ... 21 * 线程3: 7122 * 线程3: 7223 * 线程3: 7324 * 线程3: 7425 * 线程3: 7526 * 27 */
5.PS
如果你查看JDK1.5+的java.util.concurrent.*就会发现每个类都被打上了这样的注释
/** * TODO * * @since 1.5 * @author Doug Lea */public interface Condition { //TODO}
没错,这位大神就是Doug Lea 道格.李,由于其开源的并发包太过优秀所以就被纳进了JDK1.5,等等,作为一个大神怎能不让他做出更多的贡献呢?是的,java.util.*的集合框架也部分来自于Doug的贡献。参考: ,