Java多线程中,synchronized同步代码块解决多线程数据安全问题

synchronized(任意对象):就相当于给代码加锁了,任意对象就可以看成是一把锁。

synchronized(任意对象)
{
 多条语句操作共享数据的代码 
}
代码演示
public class SellTicket implements Runnable {
    private  int  tickets=100;
    private Object obj = new Object();
    @Override
    public void run() {
            while(true){
                synchronized (obj){
                    if(tickets>0){
                        try {
                            Thread.sleep(100);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票");
                        tickets--;
                    }
                }

            }
    }
}

 

public class SellTicketDemo {
    public static void main(String[] args) {
        SellTicket st= new SellTicket();

        Thread t1=new Thread(st,"窗口1");
        Thread t2=new Thread(st,"窗口2");
        Thread t3=new Thread(st,"窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

 

上一篇:Linux内核 自旋锁spin lock,教你如何用自旋锁让ubuntu死锁


下一篇:Java架构面试必知必会的微服务面试题解析