线程间通讯2 代码优化
public class practice7{
public static void main(String [] args){
Res t=new Res();
new Thread(new Input(t)).start();
new Thread(new Output(t)).start();
}
}
class Res{
private String name;
private int age;
private boolean flag=false;
public synchronized void setname(String name,int age){
if(flag)
try{wait();}catch(Exception e){}
this.name=name;
this.age=age;
flag=true;
this.notify();
}
public synchronized void outname(){
if(!flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(name+"....."+age);
flag=false;
this.notify();
}
}
class Input implements Runnable{
Res r;
Input(Res r){
this.r=r;
}
public void run(){
int x=0;
while(true){
if(x==0)
r.setname("孙月华",20);
else
r.setname("丽娟",16);
x=(x+1)%2;
}
}
}
class Output implements Runnable{
Res r;
Output(Res r){
this.r=r;
}
public void run(){
while(true)
r.outname();
}
}
死锁线程1
public class practice7 {
public static void main(String[]arr){
tic t=new tic();
Thread a1=new Thread(t);
Thread a2=new Thread(t);
a1.start();
a2.start();
}
}
class tic implements Runnable
{
private int ticketNum=1000;
private boolean flag=true;
public void run(){
while(true){
if(flag){
synchronized(new Object()){
show();
}
}
else
while(true)
this.show();
}
}