码迷,mamicode.com
首页 > 编程语言 > 详细

启动三个线程A,B,C,按ABC的顺序输出10次

时间:2015-10-25 18:04:45      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

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();
			}
		}
	}
	
	
}


启动三个线程A,B,C,按ABC的顺序输出10次

标签:

原文地址:http://my.oschina.net/xiejunbo/blog/521821

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!