为什么我的写的线程,每次都是第一个抢到呢?是我电脑性能太好了还是代码有问题?求大神解答,在线等,急急急急~
package Date_09_22;
import java.util.Random;
public class RedPacket implements Runnable {
private int count = 5;
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(this) {
while (true) {
if (count > 0) {
Random ra = new Random();
int num = ra.nextInt(9) + 1;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢了"+num+"元");
count --;
}
}
}
}
}
package Date_09_22;
public class RedPacketDemo {
public static void main(String[] args) {
RedPacket rp =new RedPacket();
Thread t1 = new Thread(rp,"张三");
Thread t2 = new Thread(rp,"李四");
Thread t3 = new Thread(rp,"王武");
Thread t4 = new Thread(rp,"小刘");
Thread t5 = new Thread(rp,"赵七");
t2.start();
t1.start();
t3.start();
t4.start();
t5.start();
}
}
这是运行结果:
李四抢了8元
李四抢了5元
李四抢了3元
李四抢了4元
李四抢了2元
|
|