java多线程快速入门(十一)

在方法上面加synchonizd用的是this锁

package com.cppdy;

class MyThread7 implements Runnable {

    private Integer ticketCount = 100;
    public boolean falg = true;

    @Override
    public void run() {
        if (falg) {
            synchronized (this) {
                while (ticketCount > 0) {
                    try {
                        Thread.sleep(50);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。");
                    ticketCount--;
                }
            }
        } else {
            while (ticketCount > 0) {
                sale();
            }
        }
    }

    public synchronized void sale() {
        if (ticketCount > 0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。");
            ticketCount--;
        }
    }
}

public class ThreadDemo7 {

    public static void main(String[] args) throws Exception {
        MyThread7 mt = new MyThread7();
        Thread thread1 = new Thread(mt, "窗口1");
        Thread thread2 = new Thread(mt, "窗口2");
        thread1.start();
        Thread.sleep(30);
        mt.falg = false;
        thread2.start();
    }

}

原文地址:https://www.cnblogs.com/jiefu/p/10015666.html