首页 > 代码库 > Java学习之多线程同步 <好程序员特训营>

Java学习之多线程同步 <好程序员特训营>

<A href="http://www.goodprogrammer.org/" target="blank">android培训</a>------我的java笔记,期待与您交流!

 

要求:用两个线程分别输出0到100之间的奇数和偶数,要求先输出10个奇数,再输出10个偶数,再输出10个奇数,以此类推

 

//Print类public class Print {	public void odd(int i){		System.out.println(Thread.currentThread().getName() + "输出:" + i);	}	public void even(int i){		System.out.println(Thread.currentThread().getName() + "输出:" + i);	}}

 

//PrintOdd.javapublic class PrintOdd extends Thread {	private Print p;	public PrintOdd(Print p) {		this.p = p;	}	public void run() {		int count = 0;//控制循环次数(10次循环后等待)		for (int i = 0; i < 100; i += 2) {			synchronized (p) {				p.odd(i);				count++;				if (count == 10) {					count = 0;					try {						p.wait();//输出10个数后该线程等待					} catch (InterruptedException e) {						e.printStackTrace();					}				}				p.notifyAll();//唤醒其他线程			}		}	}}

 

//PrintEven.javapublic class PrintEven extends Thread {	private Print p;	public PrintEven(Print p) {		this.p = p;	}	public void run(){		int count = 0;		for (int i = 1; i < 100; i += 2) {			synchronized (p) {				p.even(i);				count++;				if (count == 10) {					count = 0;					try {						p.wait();					} catch (InterruptedException e) {						e.printStackTrace();					}				}				p.notifyAll();			}		}	}}

 

//TestDemo.javapublic class TestDemo {	public static void main(String[] args) {		Print p = new Print();		new PrintEven(p).start();		new PrintOdd(p).start();	}}

 

Java学习之多线程同步 <好程序员特训营>