wait(),notify(),notifyAll(),synchronized
wait()和notify()是java.lang.Object的对象方法,synchronized是java关键字;wait()和notify()必须配合synchronized使用。
假设有
Object obj = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(obj) {
System.out.println("thread t1 start");
obj.wait();
System.out.println("this is thread t1 end");
}
}
);
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(obj) {
System.out.println("thread t2 start");
obj.notify();
System.out.println("this is thread t2 end");
}
}
);
t1.start();
t2.start();
其中obj.wait()
表示线程t1释放对象obj的锁,同时线程t1进入进入阻塞状态(注:Thread.sleep()也会阻塞线程,但是sleep()方法不会释放obj的对象锁,其他线程无法访问obj对象),obj.wait()
之后的代码不会执行,直到其他线程t2调用了obj.notify()
;
在其他线程t2调用了obj.notify()
线程t1不会立刻开始执行,需要等待线程t2的synchronized代码块执行完毕,
即代码输出表现为:
thread t1 start
thread t2 start
this is thread t2 end
this is thread t1 end
notify(),notifyAll()
notify()
方法会随机的通知一个线程去获取对象obj的锁,notifyAll()
方法通知所有线程去竞争对象obj的锁。
这里的线程是指执行了obj.wait()
方法后进入阻塞状态的线程
join()
join()
方法是Thread对象的方法。
例如:
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread t3 start");
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printTrace();
}
System.out.println("thread t3 end");
}
);
Thread t4 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread t4 start");
t3.join();
System.out.println("thread t4 end");
}
);
t3.start();
t4.start();
t3.join()
方法表示阻塞t4线程直到t3线程执行完毕,t4线程继续执行;可以简单的理解为t3的run方法被加入到了t4的run方法中,则执行结果如下:
thread t3 start
thread t4 start
thread t3 end
thread t4 end