62,635
社区成员




class TestSynchronized
{
public static void main(String[] args)
{
Ticket t = new Ticket();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class Ticket implements Runnable
{
int ticket = 100;
String str = new String("");
public void run()
{
while(true)
{
/*synchronized(str)
{
if(ticket > 0)
{
try
{Thread.sleep(100);}
catch(Exception e){}
System.out.println(Thread.currentThread().getName() + " :sales a ticket:" + ticket--);
}
}*/
sale();
}
}
public synchronized void sale()
{
if(ticket > 0)
{
try{Thread.sleep(100);}
catch(Exception e){}
System.out.println(Thread.currentThread().getName() + " :sales a ticket:" + ticket--);
}
}
}
public class TestSynchronized
{
public static void main(String[] args)
{
Ticket t = new Ticket();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class Ticket implements Runnable
{
int ticket = 100;
String str = new String(""); //这个str用于同步目的。
public void run()
{
while(true)
{
try
{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace(); // 最好加上.
}
synchronized(str)
{
if(ticket > 0)
{
System.out.println(Thread.currentThread().getName() + " :sales a ticket:" + ticket--);
}
}
if(ticket<=0) //票卖完让程序退出。
break;
}//end while
}//end run
}