同步方法解决实现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 (ticket > 0) {
            show();
        }
    }
    public synchronized void show(){
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket);
            ticket--;
        }
    }
}

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