Java线程同步卖票问题解决方案(synchronized)

关键知识点:synchronized、Runnable

synchronized:

1、使用同步代码块进行卖票:

public class TicketsCodeBlock implements Runnable { 
    private int count = 100; //总票数目 

    public static void main(String[] args) { 
        TicketsCodeBlock tickets = new TicketsCodeBlock(); 
        Thread t1 = new Thread(tickets); 
        Thread t2 = new Thread(tickets); 
        Thread t3 = new Thread(tickets); 
        t1.start(); 
        t2.start(); 
        t3.start(); 
     } 
    public void run() { 
        for (int i = 0; i < 10; i++) {
            synchronized (this) { // 同步代码块 
                if (count > 0) {
                      try { 
                        Thread.sleep(500); // 500ms 
                      } catch (Exception e){ 
                         e.printStackTrace(); 
                      } 
                      Thread t = Thread.currentThread();
                      System.out.println(t.getName() + " 剩余票的数目: " + (count--)); 
                  }
             }
         } 
    }
}

2、使用同步方法进行卖票:
public class TicketsMethod implements Runnable {
private int count = 100; //总票数目

public static void main(String[] args) { 
    TicketsMethod tickets = new TicketsMethod(); 
    Thread t1 = new Thread(tickets); 
    Thread t2 = new Thread(tickets); 
    Thread t3 = new Thread(tickets); 
    t1.start(); 
    t2.start(); 
    t3.start(); 
 } 
public void run() { 
    for (int i = 0; i < 10; i++) {
        sale();
    }

}
// 使用同步方法进行卖票
public synchronized void sale() {
if (count > 0) {
try {
Thread.sleep(500); // 500ms
} catch (Exception e){
e.printStackTrace();
}
Thread t = Thread.currentThread();
System.out.println(t.getName() + " 剩余票的数目: " + (count--));
}
}
}
}
}

你可能感兴趣的:(Java线程同步卖票问题解决方案(synchronized))