1. 程式人生 > >java三執行緒交替列印123……n

java三執行緒交替列印123……n

使用多執行緒交替列印1--n,a程序列印1,4,7,……(3n+1),b程序列印2,7,10,……(3n+2),c程序列印3,6,9,……(3n)

涉及到多執行緒的同步,阻塞,wait,notify

程式碼如下

Num.java

public class Num {
	private int num = 0;

	public Num(int num) {
		this.num = num;
	}

	public synchronized void printOne() {
		try {
			while (num%3!=1) {
				this.wait();
			}
			System.out.println(Thread.currentThread().getName() + "------->"
					+ (num++));
			Thread.sleep(1000);
			this.notifyAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void printTwo() {
		try {
			while (num%3!=2) {
				this.wait();
			}
			System.out.println(Thread.currentThread().getName() + "------->"
					+ (num++));
			
			Thread.sleep(1000);

			this.notifyAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void printThr() {
		try {
			while (num%3!=0) {
				this.wait();
			}
			System.out.println(Thread.currentThread().getName() + "------->"
					+ (num++));
			Thread.sleep(1000);
			this.notifyAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
三個執行緒類
public class PrintOne implements Runnable {
	private Num num;

	public PrintOne(Num num) {
		this.num = num;
	}

	@Override
	public void run() {
		while (true) {
			num.printOne();
		}
	}
}

public class PrintTwo implements Runnable {
	private Num num;

	public PrintTwo(Num num) {
		this.num = num;
	}

	@Override
	public void run() {
		while (true) {
			num.printTwo();
		}
	}
}

public class PrintThr implements Runnable {
	private Num num;

	public PrintThr(Num num) {
		this.num = num;
	}

	@Override
	public void run() {
		while (true) {
			num.printThr();
		}
	}
}

測試類
public class Test {
	public static void main(String[] args) {
		Num num = new Num(0);
		Thread pOne = new Thread(new PrintOne(num));
		Thread pTwo = new Thread(new PrintTwo(num));
		Thread pThr = new Thread(new PrintThr(num));
		
		pOne.setName("3n+1");
		pTwo.setName("3n+2");
		pThr.setName("3n  ");
		
		pOne.start();
		pTwo.start();
		pThr.start();
	}
}

效果
3n  ------->0
3n+1------->1
3n+2------->2
3n  ------->3
3n+1------->4
3n+2------->5

…………