java多线程模拟抢红包功能
程序员文章站
2024-02-21 18:29:16
今天有朋友问我一道面试题,有5个人抢5个红包,可重复抢,用多线程程序实现,实现方式有多种,分享一下我的思路:应用了阻塞队列的特性。
/**
* crea...
今天有朋友问我一道面试题,有5个人抢5个红包,可重复抢,用多线程程序实现,实现方式有多种,分享一下我的思路:应用了阻塞队列的特性。
/** * created by zhanglinqiang on 2016/6/23. */ public class mytest { public static void main(string[] args) throws interruptedexception { linkedblockingqueue<luckymoney> luckymoneys = new linkedblockingqueue<>(); list<futuretask> futuretasks = new arraylist<>(); //准备抢红包 for (int i = 0; i < 5; i++) { futuretask<object> futuretask = new futuretask<>(new catchluckmoney(luckymoneys, "name" + i), null); new thread(futuretask,"name"+i).start(); futuretasks.add(futuretask); } thread.sleep(5);//确保抢红包线程准备就绪 random random = new random(100); //发5个红包 for (int i = 0; i < 5; i++) { luckymoneys.put(new luckymoney("红包"+i, random.nextint(100)+1)); } //等到红包抢完 while (!luckymoneys.isempty()){ thread.sleep(1); } //终止抢红包线程 for (futuretask futuretask : futuretasks) { futuretask.cancel(true); } } } class catchluckmoney implements runnable { public catchluckmoney(linkedblockingqueue<luckymoney> luckymoneys, string name) { this.luckymoneys = luckymoneys; this.name = name; } private linkedblockingqueue<luckymoney> luckymoneys; private string name; @override public void run() { while (!thread.currentthread().isinterrupted()) { luckymoney redpackage = null; try { redpackage = luckymoneys.take(); } catch (interruptedexception e) { // e.printstacktrace(); break; } system.out.println(name + "抢到了-->" + redpackage); luckymoneys.remove(redpackage); } system.out.println("end>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+thread.currentthread().getname()); } } class luckymoney { public luckymoney(string name, integer money) { this.name = name; this.money = money; } private string name; private integer money; @override public string tostring() { return "luckymoney{" + "name='" + name + '\'' + ", money=" + money + '}'; } }
运行效果:
connected to the target vm, address: '127.0.0.1:8869', transport: 'socket' name3抢到了-->luckymoney{name='红包0', money=16} name4抢到了-->luckymoney{name='红包3', money=89} name0抢到了-->luckymoney{name='红包2', money=75} name1抢到了-->luckymoney{name='红包1', money=51} name3抢到了-->luckymoney{name='红包4', money=92} end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name0 end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name4 end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name3 disconnected from the target vm, address: '127.0.0.1:8869', transport: 'socket' end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name1 end>>>>>>>>>>>>>>>>>>>>>>>>>>>>name2 process finished with exit code 0
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。