package com.lsw.thread;
public class SocetDemo {
public static void main(String[] args) {
//創建資源對象
Resource5 r = new Resource5();
//創建任務對象
Input5 in = new Input5(r);
Output5 out = new Output5(r);
//創建線程對象
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//開啟線程
t1.start();
t2.start();
}
}
class Resource5{
String name;
String sex;
}
class Input5 implements Runnable{
private Resource5 r;
Input5(Resource5 r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x == 0){
r.name = "Tom";
r.sex = "man";
} else {
r.name = "小紅";
r.sex = "女";
}
x = (x + 1)%2;
}
}
}
class Output5 implements Runnable{
private Resource5 r;
Output5(Resource5 r){
this.r = r;
}
public void run(){
while(true){
System.out.println(r.name + "," + r.sex);
}
}
}
打印結果:為何會出現Tom,女 和 小紅,man的情況呢? 每個線程都執行的是自己獨立的任務啊
這種定義是線程不安全的,
f(x == 0){
r.name = "Tom";//這裡改變後,下面sex還沒來得及改變,另一個線程就打印了。所以出現你那種情況
r.sex = "man";
} else {
r.name = "小紅";//同上
r.sex = "女";
}
在改變r的時候,應該加同步鎖
http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html