线程的交互

public class SumTt{
	public static void main(String[] args) {
		
		SumThread sm = new SumThread();
		sm.start();
		synchronized (sm) {
			System.out.println(System.currentTimeMillis());
			System.out.println("表演开始");
			try {
				sm.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(sm.getSum());
		}
	}
}

public class SumThread  extends Thread{
	private int sum;
	@Override
	public void run() {
		synchronized (this) {
			System.out.println(System.currentTimeMillis());
			for (int i = 0; i < 3; i++) {
				sum+=1;
			}
			this.notify();
		}
	}

	public int getSum() {
		return sum;
	}

	public void setSum(int sum) {
		this.sum = sum;
	}
}

  • 前提: 多个线程操作同一个对象
  • wait线程释放锁进入阻塞状态,notify唤醒锁对象池中其中一个线程,notifyall唤醒锁对象池中所有的线程,没有线程等待,不做任何措施。
  • 注意一点:如果要把notify和wait方法放在一起用的话,必须先调用notify后调用wait,因为如果调用完wait,该线程就已经不是currentthread了。
原文地址:https://www.cnblogs.com/kungFuPander/p/11711696.html