多线程出现的问题

class Ticket1 implements Runnable {

    private int tick = 100;

    public void run() {
        while (true) {
            if (tick > 0) {
                try {
                    Thread.sleep(10); // 让出执行权,出现多线程安全问题
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "sale: "+ tick--);
            }
        }
    }
}

public class Test1 {

    public static void main(String[] args) throws InterruptedException {

        Ticket1 t = new Ticket1(); 

        Thread t1 = new Thread(t); 
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        Thread t4 = new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

你可能感兴趣的:(多线程出现的问题)