先贴出正确的代码:
1 package com.xiaobai.thread.main; 2 3 import lombok.extern.slf4j.Slf4j; 4 5 @Slf4j 6 public class ThreadMain { 7 8 private volatile static int ticket; 9 10 private static class RunningTask implements Runnable{ 11 12 public RunningTask(boolean proOrSell) { 13 this.proOrSell = proOrSell; 14 } 15 16 private boolean proOrSell = true;//如果为静态,会被实例共享 17 18 public void run() { 19 while (true) {//只同步需要同步的代码,while(true)不能放在同步里面!!否则除非线程自己wait(),永远不会轮到其他线程!! 20 synchronized (RunningTask.class) { 21 proOrSell(); 22 } 23 } 24 } 25 26 private void proOrSell() { 27 if(proOrSell) { 28 ticket++; 29 log.info("Tickets/Pro:" + ticket); 30 RunningTask.class.notifyAll(); 31 if(ticket >= 1000) { 32 try { 33 System.out.println("--------------------------------------------------------------------------------------------------------------------------------------->Pro Wait!!!!!"); 34 RunningTask.class.wait();//持有锁的本线程等待 35 } catch (InterruptedException e) { 36 37 } 38 } 39 }else { 40 System.out.println(Thread.currentThread().getName() + " take control!"); 41 if(ticket <= 100) { 42 try { 43 System.out.println(Thread.currentThread().getName() + " <=100!"); 44 System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==>Sell Wait!!!!"); 45 RunningTask.class.wait(); 46 } catch (InterruptedException e) { 47 48 } 49 }else { 50 ticket--; 51 log.info("Tickets------->Sell:" + ticket); 52 System.out.println(Thread.currentThread().getName() + " decrease tickets!"); 53 if(ticket <= 500) { 54 RunningTask.class.notifyAll(); 55 } 56 } 57 } 58 } 59 } 60 61 private static void proOrSell() { 62 Runnable task1 = new RunningTask(true); 63 Runnable task2 = new RunningTask(false); 64 Thread thread1 = new Thread(task1); 65 Thread thread2 = new Thread(task2); 66 Thread thread3 = new Thread(task2); 67 Thread thread4 = new Thread(task2); 68 thread1.start(); 69 try { 70 Thread.sleep(3000); 71 } catch (InterruptedException e) { 72 73 } 74 thread2.start(); 75 thread3.start(); 76 thread4.start(); 77 } 78 79 public static void main(String[] args) { 80 proOrSell(); 81 while (ticket <= 0) { 82 System.out.println("------------------------------------------------------->Ticket System Broken!!!!!!"); 83 System.exit(0); 84 } 85 } 86 87 }