本文共 2061 字,大约阅读时间需要 6 分钟。
之前有一个买票的案例,当时多个线程之间不是安全的,这是我们遗留的问题,今天来解决它
我们之前提到,线程不安全主要是资源被每个对象都可以使用,导致了多个线程在抢夺一份资源时,都误以为自己拿到了
那么我们就需要给这个资源加一把锁 来使用以下 synchronized
//安全的买票public class UnSafe { public static void main(String[] args) { BuyTicket station = new BuyTicket(); new Thread(station,"你").start(); new Thread(station,"别人").start(); new Thread(station,"黄牛党").start(); }}class BuyTicket implements Runnable{ private int numticket = 10; boolean flag = true;//外部停止方法 @Override public void run() { while (flag){ try { buy(); //Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } //synchronized 将其变成同步方法 private synchronized void buy() throws InterruptedException { //判断是否有票 if (numticket <= 0){ flag = false; return; } //模拟延时 Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"拿到了票---"+numticket--); }}
此时会有一些新的问题 ,我们来看看
这个票被我一个人拿了。确实别人没有抢,但是他们也没买上,这是怎么回事呢
原来 syn (简称)有偏向于最先获得锁的优先级更高的线程,所以我们需要在调用 buy()方法时 让他睡一会
//安全的买票public class UnSafe { public static void main(String[] args) { BuyTicket station = new BuyTicket(); new Thread(station,"你").start(); new Thread(station,"别人").start(); new Thread(station,"黄牛党").start(); }}class BuyTicket implements Runnable{ private int numticket = 10; boolean flag = true;//外部停止方法 @Override public void run() { while (flag){ try { buy(); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } //synchronized 将其变成同步方法 private synchronized void buy() throws InterruptedException { //判断是否有票 if (numticket <= 0){ flag = false; return; } //模拟延时 Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"拿到了票---"+numticket--); }}
这样的结果才是我们想要的
转载地址:http://wyuef.baihongyu.com/