9.6 同步和死锁 同步代码块 sysnchronized (同步对象){....} 同步方法 sysnchronized 方法返回值 方法名称(参数列别){...}
访问权限{public /default/protect/private}[final][static][synchronized] 返回值 类型 /void 方法名称(参数类型 参数名称,...)[throws Exception1,..]
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 |
package
com.java.demo9.thread;public class Info { private
String name="Tom"; private
String content="JAVA teacher"; private
boolean flag=false; public
synchronized void set (String name,String content){ if(!flag){ try{ super.wait(); }catch(Exception e){ e.printStackTrace(); } } this.setName(name); try{ Thread.sleep(90); }catch(Exception e){ e.printStackTrace(); } this.setContent(content); flag=false; super.notify(); } public
synchronized void get(){ if(flag){ try{ super.wait(); }catch(Exception e){ e.printStackTrace(); } } try{ Thread.sleep(100); }catch(Exception e){ e.printStackTrace(); } System.out.println(this.getName()+" --->"+this.getContent()); flag=true; super.notify(); } public
void setName(String name){ this.name=name; } public
void setContent(String content){ this.content=content; } public
String getName(){ return
this.name; } public
String getContent(){ return
this.content; } } |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
package
com.java.demo9.thread;public class Producer implements
Runnable { private
Info info =null; public
Producer(Info info){ this.info=info; } public
void run (){ boolean
flag=false; for(int
i=0;i<50;i++){ if(flag){ this.info.set("Tom ", "java teacher"); flag=false; }else{ this.info.set("mldn", "www.mldn.com"); flag=true; } } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
package
com.java.demo9.thread;public class Consumer implements
Runnable { private
Info info=null; public
Consumer(Info info){ this.info=info; } public
void run(){ for(int
i=0;i<50;i++){ try{ Thread.sleep(100); }catch(Exception e){ e.printStackTrace(); } this.info.get(); } }} |
线程处理必须编run();wait();sleep();jion();
原文:http://www.cnblogs.com/zhengfengshaw/p/3550050.html