多线程等待(wait)和通知(notify)
wait()用于释放锁,所以在释放之前要必须要持有对象锁,所以必须在 synchronized(obj){}内部使用wait()——wait()会使当前线程由运行状态进入等待状态(阻塞状态)(解释:就是当前线程wait()之后的代码都不会执行了,只有被唤醒后,重新竞争cpu资源,获取锁,才会执行wait()语句之后的代码)——(相当于同步阻塞)
notify()用于唤醒等待线程,并且不会立刻释放锁资源,因为要释放锁资源,所以必须 在synchronized(obj){}内部使用notify(),在加锁代码块执行完毕后才会去释放锁住资源,并运行wait()之后的代码
public static void main(String[] args) {
thread2 t = new thread2();
Thread threa = new Thread(t);
synchronized ( t) {
threa.start();
try {
System.out.println(“0000”);
t.wait();
System.out.println(“11111”);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
synchronized (this){
try {
System.out.println(“1.1.1.1.”);
Thread.sleep(1000L);
System.out.println(“2.2.2..2”);
notify();
System.out.println(“3.3.3..3”);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
结果:0000
1.1.1.1.
2.2.2..2
3.3.3..3
11111
备注:wait(),notify(),notify()都属于Object的方法;