使用同步代码块解决线程安全问题

class Ticket1 implements Runnable {

    private int tick = 100;
    Object obj = new Object();

    public void run() {
        while (true) {

            synchronized (obj) {    //同步代码块

                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(); // t本身不是线程,没有实现Thread对象

        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();
    }
}

你可能感兴趣的:(使用同步代码块解决线程安全问题)