public class TestThread
{
public static void main(String[] args)
{
ThreadTest tt=new ThreadTest();
new Thread(tt).start();
try {Thread.sleep(1);} catch (Exception e) {e.getMessage();}
tt.str=new String("method");
new Thread(tt).start();
}
}
class ThreadTest implements Runnable//extends Thread
{
public int tickets=100;
String str = new String("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}else
{
while(true)
synchronized (this)
{
{
if(tickets>0)
{
try
{
Thread.sleep(10);
} catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"代码块卖出票:"+tickets--);
}
}
}
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"方法卖出票:"+tickets--);
}
}
}