public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 5; i++) {
list.add(r.nextInt(10)+1);
}
MyMoney mm = new MyMoney(list);
new MyMoney().start();
new MyMoney().start();
new MyMoney().start();
new MyMoney().start();
new MyMoney().start();
}
}
class MyMoney extends Thread{
static private ArrayList<Integer> list = new ArrayList<>();
public MyMoney(){}
public MyMoney(ArrayList<Integer> list){
this.list=list;
}
public void run(){
for(int i=0; i<list.size()-1;i++){
synchronized(MyMoney.class){
if(list.size()==0){
break;
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName()+"抢到了"+list.get(i)+"元");
list.remove(i);
i--;
}
}
}
public class Test_meal {
/**
* 共有1000份盒饭,可以在两个窗口领取,假设每次装饭的时间是3000ms,请用线程描述取反过程,并打印剩余饭盒数量
*/
public static void main(String[] args) {
Meals m = new Meals();
m.setName("一号");
m.start();
Meals m1 = new Meals();
m1.setName("二号");
m1.start();
}
}
class Meals extends Thread{
private static int meal = 1 ;
public void run(){
while(true){
synchronized(Meals.class){
if(meal>1000){
break;
}
try {
Meals.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName()+"窗口卖出第"+meal++ +"份盒饭,总共还剩"+ (1000+1-meal++)+"份盒饭");
}
}
} |