java之多线程抢火车票的实现示例
作者:帅龍之龍
生活中有很多多线程的案例,购票就是一个很常见的问题,本文主要介绍了java之多线程抢火车票的实现示例,具有一定的参考价值,感兴趣的可以了解一下
一、创建线程的方法是实现runnable,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
*********************************/ //多个线程同时操作一个类 //火车票 public class TestTread4 implements Runnable{ //票数 private int ticketNums = 10; @Override public void run() { while (true) { if (ticketNums <= 0) { break; } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"--->拿到了第"+ticketNums-- +"张票"); } } public static void main(String[] args) { TestTread4 testTread4 = new TestTread4(); new Thread(testTread4, "小明").start(); new Thread(testTread4,"老师").start(); new Thread(testTread4,"黄牛").start(); } }
发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱.
加上锁就搞定
public class TestTread4 implements Runnable{ //票数 private int ticketNums = 10; @Override public synchronized void run() { while (true) { if (ticketNums <= 0) { break; } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"--->拿到了第"+ticketNums-- +"张票"); } } public static void main(String[] args) { TestTread4 testTread4 = new TestTread4(); new Thread(testTread4, "小明").start(); new Thread(testTread4,"老师").start(); new Thread(testTread4,"黄牛").start(); } }
当有200人抢100张票
public class TicketRunnable implements Runnable { /** * 总票数 */ private final int ticketSize = 100; /** * 抢票人数 */ private final int peopleSize = 200; /** * 票数 */ private int ticketNum; /** * 人数 */ private int peopleNum; @Override public void run() { while(ticketNum < ticketSize && peopleNum < peopleSize){ synchronized (this){ if(ticketNum < ticketSize && peopleNum < peopleSize){ if((int)(Math.random() * 20) % 2 == 1){ System.out.println(Thread.currentThread().getName() + "第" + (++peopleNum) + "个人抢到第" + (++ticketNum) + " 张票"); try { Thread.sleep(100); }catch (Exception e){ e.printStackTrace(); } }else { System.out.println(Thread.currentThread().getName() + "第" + (++peopleNum) + " 个人未抢到票"); } } } } } }
public class TestTicket { public static void main(String[] args) { TicketRunnable tr = new TicketRunnable(); Thread t1 = new Thread(tr , "窗口A"); Thread t2 = new Thread(tr , "窗口B"); Thread t3 = new Thread(tr , "窗口C"); Thread t4 = new Thread(tr , "窗口D"); t1.start(); t2.start(); t3.start(); t4.start(); } }
到此这篇关于java之多线程抢火车票的实现示例的文章就介绍到这了,更多相关java 多线程抢火车票内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!