首页 > 代码库 > 关于线程的synchronized,wait,sleep,notify的一段有趣的代码
关于线程的synchronized,wait,sleep,notify的一段有趣的代码
首先进入正题,来看代码:
public class MultiThread {
public static void main(String[] args) {
new Thread (new Thread1()).start();
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
private static class Thread1 implements Runnable{
public void run(){
synchronized(MultiThread.class){
System.out.println("enter Thread1...");
System.out.println("Thread1 is waiting ");
try{
MultiThread.class.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("thread1 is going on...");
System.out.println("thread1 is being over!");
}
}
}
private static class Thread2 implements Runnable{
public void run(){
synchronized(MultiThread.class){
System.out.println("enter Thread2...");
System.out.println("Thread2 notify other thread can release wait....");
MultiThread.class.notify();
System.out.println("thread2 is sleeping 10 m");
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("thread2 is going on...");
System.out.println("thread2 is being over!");
}
}
}
}
再来看结果:
本代码。首先按照顺序运行,执行代码:
但是继续往下执行的时候便遇到了wait方法,要知道,wait方法不仅会让出正在执行线程所用的cpu,还会将锁释放出去。而Thread1与Thread2同步,开始都有锁,但Thread1释放之后,自然而然的便会运行到Thread2了。所以便运行到了一下代码:
接下来便遇到了notify方法,唤醒等待的线程,但是呢,它只是简单的唤醒,并不会给线程加锁,所以现在有锁的还是Thread2线程。所以继续往下执行。于是便到了一下代码处:
等待睡眠时间过了以后,有执行以下代码:
到此,Thread2执行完了,便释放掉锁,也就顺理成章的执行Thread1最后的部分:
到此为止,程序运行结束!
关于线程的synchronized,wait,sleep,notify的一段有趣的代码