Java-按指定顺序执行线程

前几天,碰到一个朋友问我问题,顺手写的一个小测试案例

首先看下结果:

A:1
B:2
C:3
A:4
B:5
C:6
A:7
B:8
C:9
A:10
B:11
C:12
A:13
B:14

程序入口:

	public static void main(String[] args) throws Exception {
		ExecutorService es = Executors.newFixedThreadPool(3);
		RunVO vo=new RunVO();
		es.submit(new Run1(vo,null));
		es.submit(new Run2(vo,null));
		es.submit(new Run3(vo,null));
		es.shutdown();
	}

关键控制类

/**
 * @author MichaelKoo
 * 
 *         2017-6-12
 */
public class RunVO implements Comparable {
	private int count = 1;
	public volatile int order = 1;

	/**
	 * @param count
	 */
	public RunVO(int count) {
		super();
		this.count = count;
	}

	/**
	 * 
	 */
	public RunVO() {
		super();
	}

	public void add() {
		count++;
	}

	/**
	 * @return the count
	 */
	public int getCount() {
		return count;
	}

	public boolean exit() {
		return count == 15;
	}

	public int compareTo(RunVO o) {
		return 0;
	}

	@Override
	public String toString() {
		return "RunVO [count=" + count + ", order=" + order + "]";
	}

}

线程1

public class Run1 implements Runnable {

	private RunVO vo;

	/**
	 * @param vo
	 */
	public Run1(RunVO vo, Object next) {
		super();
		this.vo = vo;
	}

	public void run() {
		while (true) {
			synchronized (vo) {
				if (vo.exit()) {
					vo.notifyAll();
					break;
				}
				if (vo.order != 1) {
					try {
						vo.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				System.out.println("A:" + vo.getCount());

				vo.add();
				vo.order = 2;

				vo.notifyAll();
				try {
					vo.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

public class Run2 implements Runnable {
	private RunVO vo;

	/**
	 * @param vo
	 */
	public Run2(RunVO vo, Object obj) {
		super();
		this.vo = vo;
	}

	public void run() {
		while (true) {
			synchronized (vo) {
				if (vo.exit()) {
					break;
				}
				if (vo.order != 2) {
					try {
						vo.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				System.out.println("B:" + vo.getCount());
				vo.add();
				vo.order = 3;
				vo.notifyAll();
				try {
					vo.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	}

}

public class Run3 implements Runnable {

	private RunVO vo;

	/**
	 * @param vo
	 */
	public Run3(RunVO vo, Object obj) {
		super();
		this.vo = vo;
	}

	public void run() {
		while (true) {
			synchronized (vo) {
				if (vo.exit()) {
					vo.notifyAll();
					break;
				}
				if (vo.order != 3) {
					try {
						vo.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				System.out.println("C:" + vo.getCount());
				vo.add();
				vo.order = 1;
				vo.notifyAll();
				try {
					vo.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}


以上就是全部的源码,


关键的节点在于如何控制线程的顺序,这里使用的是根据标志位来标识,线程通过判断当前标识,如果是属于自己的标识就执行,反之则不执行



你可能感兴趣的:(生活上的那些事)