zoukankan      html  css  js  c++  java
  • 【JAVA】线程安全的案例

    1.什么是线程安全?

    当多个线程共享同一个全局变量,做写的操作的时候,可能会受到其他线程的干扰,导致数据有问题,这种现象叫做线程安全问题。

    2.案例

    模拟火车票卖票程序,火车车厢一般都有118个座,这里新建一个火车票类,一个方法卖票。再建一个测试类

    package lock;

    public class Ticket {

     public int count = 118;

     public int sell() {
       System.out.println(Thread.currentThread().getName() + ":还剩下" + count + "张票");
       return --count;
    }
    }
    package lock;

    public class SellerSystem {

     public static void main(String[] args) {
       Ticket ticket = new Ticket();
       new Thread(new Runnable() {
         @Override
         public void run() {
           while (ticket.sell() > 0) {
             
          }
        }
      }).start();
       new Thread(new Runnable() {
         @Override
         public void run() {
           while (ticket.sell() > 0) {

          }
        }
      }).start();
    }
    }

     

    3.为了保证线程安全问题

    第一种方法加synchronized关键字

    public synchronized int sell() {
     System.out.println(Thread.currentThread().getName() + ":还剩下" + count + "张票");
     return --count;
    }

    第二种方法,使用锁

    public int sell() {
     lock.lock();
     System.out.println(Thread.currentThread().getName() + ":还剩下" + count + "张票");
     count--;
     lock.unlock();
     return count;
    }
    Ride the wave as long as it will take you.
  • 相关阅读:
    How to check a not defined variable in javascript
    How to scroll the window using JQuery $.scrollTo() function
    jQuery图片滑动
    分享一个提供各种尺寸图片的网站
    页面添加 mask 遮罩层
    input, textarea,监听输入事件
    Google jQuery URL
    在页面内, 滑块位置的控制
    jQuery autoResize
    jQuery banner 滑动
  • 原文地址:https://www.cnblogs.com/jianpanaq/p/10264069.html
Copyright © 2011-2022 走看看