`
meikebo
  • 浏览: 16005 次
社区版块
存档分类
最新评论

JAVA同步

    博客分类:
  • 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();
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics