⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threaddemo6.java

📁 用java编写的一些初级代码
💻 JAVA
字号:
public class ThreadDemo6
{
    public static void main (String args[])
    {
	TestThread t= new TestThread();
	new Thread(t).start();
	try{Thread.sleep(1);}catch(Exception e){}
	//暂停一毫秒,将出现0
	t.str=new String("method");
	new Thread(t).start();
	//这个线程调用同步函数
    }
}
class TestThread implements Runnable 
{
    private int tickets=150;
    String str=new String("");
    public void run()
    {
	if(str.equals("method")){
	    while(true)
	    {
		sale();
	    }
	}
	else
	{
	    while(true)
	    {
		//synchronized(str){
		//使用this将同步
		synchronized(this){
		    if (tickets>0)
		    {
			try
			{
			    Thread.sleep(10);
			}
			catch (Exception e)
			{
			    System.out.println(e.getMessage());
			}
			System.out.println(Thread.currentThread().getName() +
				"is saling tickets"+tickets--);
		    }
		}
	    }
	    }
	}
	public synchronized void sale(){
	    if (tickets>0)
	    {
		try
		{
		    Thread.sleep(10);
		}
		catch (Exception e)
		{
		    System.out.println(e.getMessage());
		}
		System.out.println(Thread.currentThread().getName() +
			"is saling tickets"+tickets--);
	    }
	}
    }

⌨️ 快捷键说明

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