`
lijunaccp
  • 浏览: 153138 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JAVA 多线程1

 
阅读更多
package com.test;

public class ThreadTest
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		final Utils ts = new Utils();
		new Thread(){
			@Override
			public void run()
			{
				for (int i = 0; i < 30; i++)
				{
					ts.sub(i);
				}
			}
		}.start();
		
		for (int i = 0; i < 30; i++)
		{
			ts.main(i);
		}
	}
	


}

class Utils{
	
	private boolean flag = true;
	
	public synchronized void main(int j){
		if(!flag){
			try
			{
				this.wait();
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 5; i++)
		{
			System.out.println(j+":this's main"+i);
		}
		this.flag = false;
		this.notify();
	}
	
	public synchronized void sub(int j){
		if(flag){
			try
			{
				this.wait();
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 10; i++)
		{
			System.out.println(j+":this's sub"+i);
		}
		this.flag = true;
		this.notifyAll();
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics