zoukankan      html  css  js  c++  java
  • 多线程:购票小案例

    1.同步代码块

    public class Tickects1 implements Runnable{
    //共享数据
    private int ticket=100;
    //创建锁对象
    private Object obj=new Object();
    public void run() {
    while(true){
    //同步代码块
    synchronized(obj){
    //可能会发生线程安全问题代码
    if(ticket>0){
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"售出了第"+ticket--+"张票");
    }
    }
    }
    }
    }
    public class Demo01 {
    public static void main(String[] args) {
    Tickects1 t=new Tickects1();
    Thread t1=new Thread(t,"万达官方");
    Thread t2=new Thread(t,"淘票票");
    Thread t3=new Thread(t,"现场售票");
    t1.start();
    t2.start();
    t3.start();
    }
    }

    2.同步方法

    public class Tickects2 implements Runnable{
    //共享数据
    private int ticket=100;
    public void run() {
    while(true){
    sale();
    }
    }

    //同步方法(内置锁对象this)
    public synchronized void sale(){
    if(ticket>0){
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"售出了第"+ticket--+"张票");
    }
    }
    }
    public class Demo01 {
    public static void main(String[] args) {
    Tickects2 t=new Tickects2();
    Thread t1=new Thread(t,"万达官方");
    Thread t2=new Thread(t,"淘票票");
    Thread t3=new Thread(t,"现场售票");
    t1.start();
    t2.start();
    t3.start();
    }
    }

    3.Lock接口

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class Tickects3 implements Runnable{
    //共享数据
    private int ticket=100;
    //Lock接口实现类对象
    private Lock lock=new ReentrantLock();
    public void run() {
    while(true){
    //获取锁
    lock.lock();
    if(ticket>0){
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"售出了第"+ticket--+"张票");
    }
    //释放锁
    lock.unlock();
    }
    }
    }
    public class Demo01 {
    public static void main(String[] args) {
    Tickects3 t=new Tickects3();
    Thread t1=new Thread(t,"万达官方");
    Thread t2=new Thread(t,"淘票票");
    Thread t3=new Thread(t,"现场售票");
    t1.start();
    t2.start();
    t3.start();
    }
    }
  • 相关阅读:
    Yii2 框架目录
    实现超链接在本页面的跳转
    操作系统
    shell笔记
    软RAID5制作流程
    nginx学习之简化安装篇(一)
    Javascript中实现继承的方式
    JavaScript中的函数和C#中的匿名函数(委托、lambda表达式)
    JavaScript中变量、执行环境、作用域与C#中的异同
    Javascript与C#对变量的处理方式
  • 原文地址:https://www.cnblogs.com/nbkls/p/12778538.html
Copyright © 2011-2022 走看看