lesson5.java

来自「一些JavaAPI测试的源代码(包括一些Java中常用的数据结构类」· Java 代码 · 共 53 行

JAVA
53
字号
class ThreadDemo1
{
	public static void main(String[] args)
	{
		TestThread tt = new TestThread();
		new Thread(tt).start();
		try{Thread.sleep(10);}catch(Exception ex){}
		tt.str = new String("method");
		new Thread(tt).start();
		//new Thread(tt).start();
		//new Thread(tt).start();
	}
}

class TestThread implements Runnable
{
	int tickets = 100;
	String str = new String("");
	public void run()
	{
		//String str = new String("");
	if(str.equals("method"))
	{
		while(true)
		{sale();}
	}
	else{
		while(true)
		{
			synchronized(str)
			{
			if(tickets > 0)
			{
				try{Thread.sleep(10);}catch(Exception ex){}
				synchronized(this){}
				System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
			
			}}
		}
		}
	}
	public synchronized void sale()
	{
		if(tickets > 0)
		{
				try{Thread.sleep(10);}catch(Exception ex){}
				synchronized(str){}
				System.out.print("sale():");
				System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
			
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?