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

程序运行结果:

Java 多线程编程之“两个线程实现一个线程打印奇数,另一个线程打印偶数”_第1张图片

你可能感兴趣的:(Java)