简介
synchronized、wait和notify的实践
- synchronized是对资源进行加锁
- wait是对让线程进行等待,使线程进行阻塞状态,进入等待队列
- notify是唤醒等待队列的线程,让其重新进入就绪状态,从而能够竞争时间片,去执行线程
synchronized、notify和wait是需要进行结合使用的,下面这里为使用案例
案例
package ThreadMethod;
public class WaitAndNotifyTest {
private final static String resource="aa";
static class MyRunnbale1 implements Runnable {
@Override
public void run() {
synchronized (resource){
System.out.println(Thread.currentThread().getName()+"获取资源");
try {
System.out.println(Thread.currentThread().getName()+"调用wait,进入等待队列");
resource.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"重新获得锁");
}
}
}
static class MyRunnbale2 implements Runnable{
@Override
public void run() {
synchronized (resource){
System.out.println(Thread.currentThread().getName()+"获取资源");
resource.notify();
System.out.println(Thread.currentThread().getName()+"调用notify");
}
}
}
public static void main(String[] args) throws InterruptedException {
MyRunnbale1 myRunnbale1 = new MyRunnbale1();
Thread thread = new Thread(myRunnbale1);
MyRunnbale2 myRunnbale2 = new MyRunnbale2();
Thread thread1 = new Thread(myRunnbale2);
thread.start();
Thread.sleep(300);
thread1.start();
}
}
|