标签:
package jun; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 启动三个线程A,B,C,按ABC的顺序输出10次 * * @author xiejunbo * */ public class ABC { private int cond = 0;//控制ABC输出 private Lock lock = new ReentrantLock();//通过jdk的锁来保证线程访问的互斥 private Condition condition = lock.newCondition();//线程协作 public static void main(String[] args) { ABC abc = new ABC(); ThreadA ta = abc.new ThreadA(); ThreadB tb = abc.new ThreadB(); ThreadC tc = abc.new ThreadC(); ExecutorService executor = Executors.newFixedThreadPool(3);//通过线程池执行 for (int i = 0; i < 10; i++) { executor.execute(ta); executor.execute(tb); executor.execute(tc); } executor.shutdown(); } class ThreadA implements Runnable { public void run(){ lock.lock();//加锁 try { while (true) { if(cond % 3 == 0) { System.out.print(cond + "A "); cond++; condition.signalAll(); break; }else{ try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } } finally { lock.unlock();//解锁 } } } class ThreadB implements Runnable{ public void run(){ lock.lock(); try { while (true) { if (cond % 3 == 1) { System.out.print(cond + "B "); cond++; condition.signalAll(); break; } else { try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } } finally { lock.unlock(); } } } class ThreadC implements Runnable { public void run(){ lock.lock(); try { while(true){ if(cond % 3 == 2){ System.out.println(cond + "C "); cond++; condition.signalAll(); break; }else{ try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } } finally { lock.unlock(); } } } }
标签:
原文地址:http://my.oschina.net/xiejunbo/blog/521821