zoukankan      html  css  js  c++  java
  • 经典多线程问题 (一)-多线程售票

    1.0 synchronized

      

    /**
     * @ClassName Question11
     * @Description: 经典多线程问题-多线程售票
     * @Author xtanb
     * @Date 2019/10/22
     * @Version V1.0
     **/
    class Ticket{
        private int num = 300;
    
        public synchronized void sales(){
            if(num>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+ num-- +"张票,"+"剩余"+num+"张票");
            }
        }
    }
    public class Question11 {
        public static void main(String[] args) {
            Ticket ticket = new Ticket();
            new Thread(()->{
                for(int i=0;i<100;i++){
                    ticket.sales();
                }
            },"A").start();
            new Thread(()->{
                for(int i=0;i<100;i++){
                    ticket.sales();
                }
            },"B").start();
            new Thread(()->{
                for(int i=0;i<100;i++){
                    ticket.sales();
                }
            },"C").start();
        }
    }

    2.0 ReentrantLock

    package com.example.demo.study.questions;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * @ClassName Question12
     * @Description: TODO
     * @Author xtanb
     * @Date 2019/10/22
     * @Version V1.0
     **/
    class Tickets{
        private int num = 300;
        private Lock lock = new ReentrantLock();
    
        public void sales(){
           try{
               lock.lock();
               if(num>0){
                   System.out.println(Thread.currentThread().getName()+"卖出了第"+ num-- +"张票,"+"剩余"+num+"张票");
               }
           }catch (Exception e){
               e.printStackTrace();
           }finally {
               lock.unlock();
           }
        }
    }
    public class Question12 {
        public static void main(String[] args) {
            Tickets tickets = new Tickets();
            new Thread(()->{
                for(int i=0;i<100;i++){
                    tickets.sales();
                }
            },"A").start();
            new Thread(()->{
                for(int i=0;i<100;i++){
                    tickets.sales();
                }
            },"B").start();
            new Thread(()->{
                for(int i=0;i<100;i++){
                    tickets.sales();
                }
            },"C").start();
        }
    }
  • 相关阅读:
    多线程伪共享FalseSharing
    C语言restrict限定符
    Linux线程基础函数
    Linux信号函数
    C函数前向声明省略参数
    12.2 关闭DLM 自动收集统计信息 (SCM0)ORA-00600之[ksliwat: bad wait time]
    pdb的数量限制
    关闭或开启memory_target
    OSWATCH安装
    参数SID写错,ERROR OGG-00664 ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist
  • 原文地址:https://www.cnblogs.com/helloworldmybokeyuan/p/11717897.html
Copyright © 2011-2022 走看看