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();
    }
    }
  • 相关阅读:
    jstl嵌套以及输出json的逗号
    关闭win10 更新以后自动重启
    maven 配置错误。
    SQL SERVER 订阅发布在restore DB以后的问题
    Unable to convert MySQL date/time value to System.DateTime
    sql server恢复卡在restoring的解决方法
    打开Excel时总是运行Windows Installer(Visual studio)解决方法
    单元测试用excel connstr
    node.js调试
    javascript数组对象实例方法
  • 原文地址:https://www.cnblogs.com/nbkls/p/12778538.html
Copyright © 2011-2022 走看看