java 线程学习(2)(二)

2014-11-24 03:14:05 · 作者: · 浏览: 4
t2.start();

}

}

//notifyAll();

*/

/*

//上面代码的优化

class Res

{

private String name;

private String sex;

private boolean flag=false;

public synchronized void set(String name,String sex)

{

if(flag)

try{this.wait();}catch(Exception e){}

this.name=name;

this.sex=sex;

flag=true;

this.notify();

}

public synchronized void out()

{

if(!flag)

try{this.wait();}catch(Exception e){}

System.out.println(name+"-----"+sex);

flag=false;

this.notify();

}

}

class Input implements Runnable

{

private Res r;

Object obj=new Object();

Input(Res r)

{

this.r=r;

}

public void run()

{

int x=0;

while(true)

{

if(x==0)

r.set("mike","man");

else

r.set("丽丽","女女女女女");

x=(x+1)%2;

}

}

} www.2cto.com

class Output implements Runnable

{

private Res r;

Output(Res r)

{

this.r=r;

}

public void run()

{

while(true)

r.out();

}

}

class Test

{

public static void main(String[] args)

{

Res r=new Res();

new Thread(new Input(r)).start();

new Thread(new Output(r)).start();

}

}

*/


摘自 一路向北