欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Java线程卖票问题

时间:2023-06-17

关于线程安全的演示代码

public class MyRunnable implements Runnable{ int i = 100; @Override public void run() { while (true){ if (i<1){ System.out.println("票卖完了"); break; } try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":正在出售第"+i+"张票"); --i; } }}

public class ThreadTest { public static void main(String[] args) { MyRunnable my = new MyRunnable(); Thread thread1 = new Thread(my, "窗口1"); Thread thread2 = new Thread(my, "窗口2"); Thread thread3 = new Thread(my, "窗口3"); Thread thread4 = new Thread(my, "窗口4"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); }}


出现卖重复票,漏票,负数票问题。

使用synchronized关键字解决问题

public class MyRunnable implements Runnable{ int i = 100; @Override public void run() { while (true){ //票卖完结束 if (sellTickets())break; } } //同步方法 public synchronized boolean sellTickets(){ if (i<1){ System.out.println("票卖完了"); return true; } try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":正在出售第"+i+"张票"); --i; return false; }}

使用Lock锁

import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class MyRunnable implements Runnable{ int i = 100; Lock lock = new ReentrantLock(); @Override public void run() { while (true){ lock.lock(); //票卖完结束 if (i<1){ System.out.println("票卖完了"); break; } try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":正在出售第"+i+"张票"); --i; try{ }finally { lock.unlock(); } } }

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。