好友
阅读权限20
听众
最后登录1970-1-1
|
Java多线程synchronized,wait和notify的使用
前言
- 这段时间再看Java多线程,后面的wait()和notify()总是不知道什么时候用或者说怎么用
- synchronized虽然知道这个的用法,但是却不知道在哪里使用合适
- 今天晚上看了一篇文章,然后自己分析了一下,终于搞懂了,这篇帖子分享给有和我一样问题的小伙伴.
public class DemoNumberLimit{
public static void main(String args[]){
Object obj = new Object();
Thread threadOne = new Thread(){
public void run(){
for (int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
//华丽的分割线
for(int i=0;i<50;i++)
System.out.print("=");
System.out.println(); //换行
//同步
synchronized(obj){
obj.notify();
}
System.out.println("第一个线程接着执行");
for(int i = 51;i<101;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println("线程1执行完成");
}
};
//线程2
Thread threadTwo = new Thread(){
public void run(){
synchronized(obj){
try{
obj.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("线程2:");
System.out.println("线程1的上半部分执行完成,开始执行下半部分");
}
}
};
threadOne.start();
threadTwo.start();
threadOne.setName("One");
threadTwo.setName("Two");
}
}
- 我在这里贴出运行结果图,帮助大家理解
One:0
One:1
One:2
One:3
One:4
One:5
One:6
One:7
One:8
One:9
One:10
One:11
One:12
One:13
One:14
One:15
One:16
One:17
One:18
One:19
One:20
One:21
One:22
One:23
One:24
One:25
One:26
One:27
One:28
One:29
One:30
One:31
One:32
One:33
One:34
One:35
One:36
One:37
One:38
One:39
One:40
One:41
One:42
One:43
One:44
One:45
One:46
One:47
One:48
One:49
==================================================
第一个线程接着执行
线程2:
线程1的上半部分执行完成,开始执行下半部分
One:51
One:52
One:53
One:54
One:55
One:56
One:57
One:58
One:59
One:60
One:61
One:62
One:63
One:64
One:65
One:66
One:67
One:68
One:69
One:70
One:71
One:72
One:73
One:74
One:75
One:76
One:77
One:78
One:79
One:80
One:81
One:82
One:83
One:84
One:85
One:86
One:87
One:88
One:89
One:90
One:91
One:92
One:93
One:94
One:95
One:96
One:97
One:98
One:99
One:100
线程1执行完成
- 代码分析:
- 首先看看
threadOne 这个线程里面的synchronized 从这里开始一直到threadTwo 线程的大括号结束,可以看做是一整块代码块.
- 然后因为
synchronized 和下面的线程2是一个整体所以会先执行线程2里面的两条输出语句,然后在执行线程1中后面那个for循环
- 这些仅仅是我个人理解,如有不足请留言指出.
- 其他问题:
- 线程1的
synchronized 语句后面的输出语句第一个线程接着执行为什么跳过for循环直接执行了线程2然后在执行线程1中的for循环.
- 为什么要先写
notify() 然后在写wait()
|
免费评分
-
查看全部评分
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|