同步代码块解决实现Runnable多线程安全问题

package com.yby7;
import java.util.function.ObjDoubleConsumer;
public class WindowTest1 {
    public static void main(String[] args) {
        window1 p = new window1();

        Thread t1 = new Thread(p);
        Thread t2 = new Thread(p);
        Thread t3 = new Thread(p);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}
class window1 implements Runnable {
    private int ticket = 100;
    Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (obj) {//锁(同步监视器)-->任何一个类的对象都可以是锁
                if (ticket > 0) {//锁-->要求多线程共用同一个锁
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}

你可能感兴趣的:(安全,java,开发语言,后端)