抢红包例子:
RedThread,发起红包线程。
GrabThread,抢红包线程。
package com.what21.thread;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class RedThread extends Thread {
private Map threadMap = new Hashtable();
private Map moneyMap = new LinkedHashMap();
// 红包总额
int sum;
// 当前剩余红包
private int curtSum;
// 红包个数
int count;
// 当前红包个数
private int curtCount;
public RedThread(int sum,int count){
this.sum = sum;
this.curtSum = sum;
this.count = count;
this.curtCount = count;
}
@Override
public void run() {
while(true){
Main.threadSleep(10*100);
println();
if(curtCount<=0){
break;
}
}
}
private void println(){
Set keySet = moneyMap.keySet();
if(keySet.size() > 0 ){
System.out.println("================================");
for(String key : keySet){
System.out.println(key + " 抢到: " + moneyMap.get(key));
}
System.out.println("================================");
}else{
System.out.println("================================");
System.out.println("=========>>>没人抢红包");
System.out.println("================================");
}
}
/**
* 准备抢
*
* @param thread
*/
public void prepare(Thread thread){
System.out.println(thread.getName() + ",要抢红包");
this.threadMap.put(thread.getName(), thread);
}
/**
* 抢红包
*
* @param thread
*/
public void grab(GrabThread thread){
synchronized(this){
// 抢红包
thread.setMoney(getRed());
}
}
/**
* 抢完成
*
* @param thread
*/
public void finsh(GrabThread thread){
this.moneyMap.put(thread.getName(), thread.getMoney());
this.threadMap.remove(thread.getName());
}
/**
* @return
*/
private int getRed(){
curtCount--;
int money = 0;
if(curtCount==0){
money = curtSum;
}else{
Random random = new Random();
while(true){
money = random.nextInt(curtSum);
if(money > 0 && money
break ;
}
}
curtSum = curtSum - money;
}
return money;
}
}package com.what21.thread;
public class GrabThread extends Thread {
// 抢到的红包
private int money;
private RedThread redThread;
public GrabThread(String name,RedThread redThread){
setName(name);
this.redThread = redThread;
}
@Override
public void run() {
// 1. 准备抢
redThread.prepare(this);
// 2. 抢中......
redThread.grab(this);
// 3. 已抢到
redThread.finsh(this);
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}package com.what21.thread;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
int money = 100;
int count = 5;
// 红包线程
RedThread redThread = new RedThread(money,count);
redThread.start();
// A抢红包
GrabThread a = new GrabThread("a",redThread);
a.start();
// B抢红包
GrabThread b = new GrabThread("b",redThread);
b.start();
// C抢红包
GrabThread c = new GrabThread("c",redThread);
c.start();
// D抢红包
GrabThread d = new GrabThread("d",redThread);
d.start();
// E抢红包
GrabThread e = new GrabThread("e",redThread);
e.start();
}
/**
* 线程休息
*
* @param millis
*/
public static void threadSleep(long millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}