zoukankan      html  css  js  c++  java
  • 线程不安全

    1.下面这一例子会造成线程不安全 
     会取出负数,会同时一起抢     要是剩最后一张票的时候
    会同时取出一,这样就造成线程不安全
    
    //不安全买票
    public class UnsafeBuyTicket {
        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 ticketNnums = 10;
        boolean flag = true;//外部停止
        public void run(){
            //买票
            while(flag){
                try {
                    buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        private void buy() throws InterruptedException {
            //判断是否有票
            if (ticketNnums<=0){
                flag = false;
                return;
            }
            //模拟延时
            Thread.sleep(1000);
            //买票
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNnums--);
        }
    }
    
    
    ------------------------------------------------------------------------------------
    2.
    在buys()方法前面加synchronized它是同步方法锁的是(this)当前这个方法
    synchronized 作用是使当前的线程能有序地进出

    public class UnsafeBuyTicket { 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 ticketNnums = 10; boolean flag = true;//外部停止 public void run(){ //买票 while(flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } private synchronized void buy() throws InterruptedException { //判断是否有票 if (ticketNnums<=0){ flag = false; return; } //模拟延时 Thread.sleep(1000); //买票 System.out.println(Thread.currentThread().getName()+"拿到"+ticketNnums--); } }
  • 相关阅读:
    第一章
    第一章 计算机系统漫游
    hihocoder #1014 : Trie树
    第一章
    来个小目标
    poj 1056 IMMEDIATE DECODABILITY
    poj 2001 Shortest Prefixes
    __name__ 指示模块应如何被加载
    Python 常用函数time.strftime()简介
    CentOS安装beEF做XSS平台
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12487431.html
Copyright © 2011-2022 走看看