欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

JAVA同步,

来源: javaer 分享于  点击 46196 次 点评:190

JAVA同步,


两个线程共用的一个类的一个实例

package com.syn.test;

public class TestObject {

private String name;
private boolean flag=true;

public TestObject(String name)
{
this.name=name;
}

public synchronized String getName()
{
try
{
System.out.println("begin get");
while(!flag)
{
wait();
}
flag=true?(flag=false):(flag=true);
System.out.println("over get");
notify();
}catch(Exception e)
{
e.printStackTrace();
}
return name;
}

public synchronized void setName(String name)
{
try
{
System.out.println("begin set");
while(!flag)
{
wait();
}
flag=true?(flag=false):(flag=true);
this.name=name;
System.out.println("over set");
notify();
}catch(Exception e)
{
e.printStackTrace();
}
}

}

两个线程:线程TestThreadOne和TestThreadTwo.
TestThreadOne代码如下:

package com.syn.test;

public class TestThreadOne extends Thread{

private TestObject object;

public TestThreadOne(TestObject object)
{
this.object=object;
}

public void run()
{
while(true)
{
object.getName();
}
}

}

TestThreadTwo代码如下:

package com.syn.test;

public class TestThreadTwo extends Thread{

private TestObject object;

public TestThreadTwo(TestObject object)
{
this.object=object;
}

public void run()
{
while(true)
{
object.setName("two");
}
}

}

调用线程如下:

package com.syn.test;

public class Main {

public static void main(String[] args)
{
TestObject object = new TestObject("object");
TestThreadOne oneThread = new TestThreadOne(object);
TestThreadTwo twoThread = new TestThreadTwo(object);
oneThread.start();
twoThread.start();
}

}

相关文章

    暂无相关文章
相关栏目:

用户点评