线程间通讯
同步的前提:
1.必须要有两个或者两个以上的线程
2.必须是多个线程使用同一个锁。
必须保证同步中只能有一个线程在运行
好处:解决了多线程的安全问题。
弊端:消耗了运算资源
死锁:同步中嵌套同步,而锁却不同。
线程间通讯:
其实就是多给线程在操作同一个资源,但是操作动作不同。
--------------------------------------------------------------------------------
class Res{
String name;
String sex;
}
class Input implements Runnable{
private Res r;
Object aa=new Object();
Input(Res r){
this.r=r;
}
public void run(){
int x=0;
while(true){
synchronized(aa){
/*
(aa)这里是错误的,两个线程使用的不是同一个锁,要保证锁的唯一性
1.去掉上面的 Object aa=new Object(); aa改为 类名.class ,因为建立一个类也是建立一个对象,而建立的类是唯一的,这样才算使用同一个锁。
2.去掉上面的 Object aa=new Object(); aa改为 r ,r也是唯一的(理由看下面)
*/
if(x==0){
r.name="丽丽";
r.sex="女";
}else{
r.name="lisi";
r.sex="nan";
}
x=(x+1)%2;
}
}
}
}
class Output implements Runnable{
private Res r;
Object aa=new Object();
Output(Res r){
this.r=r;
}
public void run(){
while(true){
synchronized(aa){
System.out.println(r.name+"...."+r.sex);
}
}
}
}
class Test{
public static void main(String[] args){
Res r=new Res(); //这里只有一个对象r,保证了唯一性.
Input a=new Input(r); //他们都使用了r这个对象,传进去了,保证了大家都有
Output b=new Output(r); //他们都使用了r这个对象,传进去了,保证了大家都有
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.start();
t2.start();
}
}
浙公网安备 33010602011771号