第一题
import java.util.Arrays;
import java.util.Random;
public class ceshione {
public static void main(String[] args) {
Ticket2 runTicekt = new Ticket2();
Thread th1 = new Thread(runTicekt, "A");
Thread th2 = new Thread(runTicekt, "B");
th1.start();
th2.start();
}
}
class Ticket2 implements Runnable {
String[] s = { "macBookPro:8988","三星note7:5695","小米4:2688","联想P612:866","iphone7:5688" };
Object mutex = new Object();// 锁
public void chou() {
synchronized (mutex)// 当操作的是共享数据时,
{
Random random = new Random();
if(s.length - 1==0){
String num[]=s[0].split(":");
System.out.println(Thread.currentThread().getName() + "抽到了" + num[0]+" 价值:"+num[1]);
s[0] = s[s.length - 1];
// 数组缩容
s = Arrays.copyOf(s, s.length - 1);
}
else{
int a = random.nextInt(s.length - 1);
String num[]=s[a].split(":");
System.out.println(Thread.currentThread().getName() + "抽到了" + num[0]+" 价值:"+num[1]);
s[a] = s[s.length - 1];
// 数组缩容
s = Arrays.copyOf(s, s.length - 1);
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while (s.length > 0) {
chou();
if(s.length==1){
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} |