黑马程序员技术交流社区
标题:
用单例弄出来的两个线程通讯问题!求优化。。。
[打印本页]
作者:
skill20
时间:
2014-4-23 18:27
标题:
用单例弄出来的两个线程通讯问题!求优化。。。
本帖最后由 skill20 于 2014-4-23 19:13 编辑
public class LockTest
{
public static void main(String[] args)
{
Thread t1 = new Thread(new InterPut());
Thread t2 = new Thread(new OutPut());
t1.start();
t2.start();
}
}
class InterPut implements Runnable
{
Person a = Person.getS();
boolean f;
public void run()
{
int x = 0;
while(true)
{
if(x == 0)
a.set("zhangya_________",23);
else
a.set("chenghu——————————————",26);
x = (x + 1)%2;
}
}
}
class OutPut implements Runnable
{
Person b = Person.getS();
public void run()
{
while(true)
{
b.get();
}
}
}
class Person
{
private static boolean flag;
private static String name;
private static int age;
private static Person s = new Person("lishi",45);
private Person(String name, int age)
{
s.name = name;
s.age = age;
}
public static Person getS()
{
return s;
}
public synchronized void set(String name , int age)
{
if(flag == true)
try{ s.wait();}
catch(Exception e){}
s.name = name;
s.age = age;
flag = true;
s.notify();
}
public synchronized void get()
{
if(flag == false)
try{ s.wait();}
catch (Exception e){}
System.out.println(s.name + s.age);
flag = false;
s.notify();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2