스 레 드 의 상호작용

1306 단어 threadcStringClass
class Calculator extends Thread {
	int total=0;

	public void run() {
		synchronized (this) {
			for (int i = 0; i < 101; i++) {
				total += i;
			}
			notifyAll();
		}	
		//               
		
	}
}

/**
 *          
 * 
 * @author leizhimin 2008-9-20 11:15:22
 */
public class ReaderResult extends Thread {
	Calculator c;

	public ReaderResult(Calculator c) {
		this.c = c;
	}

	public void run() {
		synchronized (c) {
//			try {
//				System.out.println(Thread.currentThread() + "      。。。");
//				c.wait();
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//			System.out.println(Thread.currentThread() + "     :" + c.total);
			if(c.total==0){
				try {
					System.out.println(Thread.currentThread() + "      。。。");
					c.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread() + "     :" + c.total);
		}
	}

	public static void main(String[] args) {
		Calculator calculator = new Calculator();
		
		//       ,        
		new ReaderResult(calculator).start();
		new ReaderResult(calculator).start();
		new ReaderResult(calculator).start();
		//       
		calculator.start();//         
	}
}

좋은 웹페이지 즐겨찾기