美文网首页
Java线程同步卖票问题解决方案(synchronized)

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

作者: ShereenAo | 来源:发表于2016-12-09 00:59 被阅读0次

    关键知识点: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)

          本文链接:https://www.haomeiwen.com/subject/hkhemttx.html