[Java] 纯文本查看 复制代码
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test01 {
/**
* 定义一个数组 { "橘子", "桃子", "李子", "榴莲", "香蕉", "樱桃" }
* 分三条线程abc去随机抢水果;抢到的水果不能重复
* 抢完水果后打印谁抢了多少个
* @param args
*/
public static void main(String[] args) {
String[] arr = {"橘子", "桃", "李子", "榴莲", "香蕉", "樱桃"};
MyRunnable mr = new MyRunnable(arr);
Thread t1 = new Thread(mr, "A");
Thread t2 = new Thread(mr, "B");
Thread t3 = new Thread(mr, "C");
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable {
private int count = 0;
private List<String> list;
private String[] arr;
private Random rd;
private int countA = 0;
private int countB = 0;
private boolean flag = true;
public MyRunnable(String[] arr) {
super();
list = new ArrayList<String>();
for (String string : arr) {
list.add(string);
}
this.arr = arr;
rd = new Random();
}
@Override
public void run() {
while(true){
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(this) {
if (count >= arr.length) {
break;
}
String name = Thread.currentThread().getName();
if ("A".equals(name)) {
countA ++;
} else if ("B".equals(name)) {
countB++;
}
int index = rd.nextInt(list.size());
System.out.println(name + "获取到了" + list.get(index));
list.remove(index);
}
count++;
}
synchronized (this) {
if (flag) {
System.out.println("A一共获取到了" + countA + "个");
System.out.println("B一共获取到了" + countB + "个");
System.out.println("C一共获取到了" + (count-countA-countB) + "个");
flag = false;
}
}
}
}