日期:2014-05-20 浏览次数:20748 次
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 }
------解决方案--------------------
我试过了,你让程序多运行几次就不是只有一个线程了
------解决方案--------------------