关于synchronized!
各位谁知道我这程序怎么一直都一个线程工作啊?去掉synchronized后多线程。怎么回事啊?
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 }
[解决办法]
我试过了,你让程序多运行几次就不是只有一个线程了
[解决办法]