1. 程式人生 > >Java 多執行緒程式設計之“兩個執行緒實現一個執行緒列印奇數,另一個執行緒列印偶數”

Java 多執行緒程式設計之“兩個執行緒實現一個執行緒列印奇數,另一個執行緒列印偶數”

題目:t從0到N,一個執行緒列印奇數,一個執行緒列印偶數,按順序打印出來。

           最終列印結果:0,1,2,3,4,...,N;

           思路:兩個執行緒間的通訊採用等待,喚醒方法——列印奇偶數由flag控制,當flag為真時列印偶數;

列印類Print:

package JiOuPrint;

/*多執行緒列印奇數偶數*/

public class Print {
	private int i=-1;
	boolean flag=true;//當flag為true時列印偶數;
	

	public Print(int i, boolean flag) {
		super();
		this.i = i;
		this.flag = flag;
	}
	
	public Print() {
		super();
	}
	
	
	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}
	
	public synchronized void prtjishu() {
		if(flag==true) {
			try {
				wait();
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		i+=1;
		String name=Thread.currentThread().getName();
		System.out.println(name+"列印數字"+i);
		flag=true;
		notify();
	}
	
	public synchronized void prtoushu() {
		if(flag!=true) {
			try {
				wait();
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		i+=1;
		String name1=Thread.currentThread().getName();
		System.out.println(name1+"列印數字"+i);
		flag=false;
		notify();
	}	
}

列印奇數類:

package JiOuPrint;

public class Jishuprint extends Thread{
	private Print prt;

	public Jishuprint(Print prt) {
		super();
		this.prt = prt;
	}
	public Jishuprint() {
		super();
	}

	public Print getPrt() {
		return prt;
	}

	public void setPrt(Print prt) {
		this.prt = prt;
	}
	
	public void run() {
		jishuprt();
	}

	private void jishuprt() {
		for(int j=0;j<100;j++) {
			try {
				Thread.currentThread().sleep(300);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
			prt.prtjishu();
		}
	}
}

列印偶數的類:

package JiOuPrint;

public class Oushuprint extends Thread {
	private Print prt;

	public Oushuprint(Print prt) {
		super();
		this.prt = prt;
	}
	public Oushuprint() {
		super();
	}
	
	public Print getPrt() {
		return prt;
	}

	public void setPrt(Print prt) {
		this.prt = prt;
	}
	
	public void run() {
		Oushuprt();
	}

	private void Oushuprt() {
		for(int j=0;j<100;j++) {
			try {
			Thread.currentThread().sleep(300);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		prt.prtoushu();
		}
	}
}

程式執行結果: