Java线程通信

示例代码:

//线程通信。如下的三个关键字使用的话,都得在同步代码块或同步方法中。
//wait():一旦一个线程执行到wait(),就释放当前的锁。
//notify()/notifyAll():唤醒wait的一个或所有的线程
//使用两个线程打印 1-100. 线程1, 线程2 交替打印
class PrintNum implements Runnable {
	int num = 100;
	Object obj = new Object();
	
	@Override
	public void run() {
		while(true) {
			//synchronized (this) {
			synchronized (obj) {
				//this.notify();
				obj.notify();
				if (num > 0) {
					try {
						Thread.currentThread().sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + ":" + num--);
				} else {
					break;
				}
				try {
					//this.wait();
					obj.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

public class TestCommunication {
	public static void main(String[] args) {
		PrintNum p = new PrintNum();
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(p);
		
		t1.start();
		t2.start();
	}
}


猜你喜欢

转载自blog.csdn.net/u013453970/article/details/48209583