需求
代码
- 使用Callable 方便返回执行的结果:每个线程的发送礼物的数量
- 礼物清单:共享资源,方便上锁
- 礼物数量:线程变量,每个线程发送礼物的数量
public class SendGiftThread implements Callable<Integer> {
private ArrayList<String> giftList;
private int count = 0;
public SendGiftThread(ArrayList<String> giftList) {
this.giftList = giftList;
}
public int getCount() {
return count;
}
@Override
public Integer call() throws Exception {
Random random = new Random();
while (giftList.size() > 10){
synchronized (giftList){
if (giftList.size() > 10){
int index = random.nextInt(giftList.size());
String remove = giftList.remove(index);
count++;
System.out.println(Thread.currentThread().getName() + "送出了" + remove + ",已送出" + count + "个礼物");
}
}
}
return count;
}
}
- 创建两个Callable对象
- 使用
未来任务FutureTask
进行封装 - 创建两个线程
public static void main(String[] args) {
ArrayList<String> giftList = new ArrayList<>();
String[] names = {"口红", "手机", "电脑", "手表", "鞋子", "衣服", "裤子", "帽子", "围巾", "手套", "袜子", "饰品", "包包", "眼镜", "钱包", "皮带", "项链", "手链", "戒指", "耳环"};
Random random = new Random();
for (int i = 0; i < 100; i++) {
giftList.add(names[random.nextInt(names.length)]+"-"+i);
}
SendGiftThread sendGiftThread1 = new SendGiftThread(giftList);
SendGiftThread sendGiftThread2 = new SendGiftThread(giftList);
Future<Integer> future1 = new FutureTask<>(sendGiftThread1);
Future<Integer> future2 = new FutureTask<>(sendGiftThread2);
Thread thread1 = new Thread((Runnable) future1, "小红");
Thread thread2 = new Thread((Runnable) future2, "小明");
thread1.start();
thread2.start();
try {
System.out.println("小红送出了" + future1.get() + "个礼物");
System.out.println("小明送出了" + future2.get() + "个礼物");
} catch (Exception e) {
e.printStackTrace();
}
}