java–基础–17.8–线程–wait方法与sleep方法区别
1、介绍
wait:线程间的通讯的问题,需要等待别的线程唤醒。
sleep:自己控制线程的运行状态 ,隔了一段时间自动醒过来。
wait:方法释放了锁
sleep:方法没有释放锁
wait:只能在同步控制方法或者同步控制块里面使用
sleep:在任何地方使用
2、代码验证
2.1、sleep验证
public class Demo2 {
public static void main(String[] args) {
Demo2 d = new Demo2();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (d) {
System.out.println("修改状态的sleep线程执行...");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("状态值修改成功。。。");
}
}
}).start();
}
}
修改状态的sleep线程执行…
状态值修改成功。。。
2.2、wai验证
public class Demo3 {
private volatile int signal;
public synchronized void set () {
signal = 1;
notifyAll(); // notify方法会随机叫醒一个处于wait状态的线程
// notifyAll叫醒所有的处于wait线程,争夺到时间片的线程只有一个
System.out.println("叫醒所有的处于wait线程...之后休眠3秒");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized int get () {
long begin = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + " get方法开始..."+begin);
if(signal != 1) {
try {
wait();
System.out.println("叫醒之后");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " get方法结束..."+(System.currentTimeMillis()-begin));
return signal;
}
public static void main(String[] args) throws InterruptedException {
Demo3 d = new Demo3();
Runnable t1 = new Runnable() {
@Override
public void run() {
d.set();
}
};
Runnable t2 = new Runnable() {
@Override
public void run() {
d.get();
}
};
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
new Thread(t2).start();
Thread.sleep(1000);
new Thread(t1).start();
}
}