[Java] 纯文本查看 复制代码 public class Demo2 {
public static void main(String[] args) {
//开启1线程
new mythread("老大").start();
//开启2线程
new mythread("老二").start();
//开启3线程
new mythread("老三").start();
//开启4线程
new mythread("老四").start();
//开启5线程
new mythread("老五").start();
}
}
class mythread extends Thread {
//设置共享变量
private static int packet = 5;
//有参构造方法
public mythread(String name) {
//调用父类设置姓名
super(name);
}
//重写run方法
public void run() {
//创建循环
while (true) {
//同步代码
synchronized (Thread.class) {
//判断抢红包次数
if (packet <= 0) {
//退出循环
break;
}
//异常
try {
//300ms延时
Thread.sleep(300);
//异常
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取范围在1-10元之间,随即钱数
int money = (int)(Math.random()*10+1);
//开抢
System.out.println(getName() + "抢了" + money + "元");
//抢完红包数减一
packet--;
}
}
}
} |