码迷,mamicode.com
首页 > 编程语言 > 详细

关于线程的synchronized,wait,sleep,notify的一段有趣的代码

时间:2017-07-17 12:34:16      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:tar   同步   notify   images   dex   rup   http   str   唤醒   

首先进入正题,来看代码:

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的一段有趣的代码

标签:tar   同步   notify   images   dex   rup   http   str   唤醒   

原文地址:http://www.cnblogs.com/1987721594zy/p/7193600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!