public class ThreadTest {
@Test
public void test() {
Vector<Thread> deadThreads = new Vector<>();
Object o = new Object();
Tick tick = new Tick();
for (int i = 0; i < 1000; i++) {
new Thread(() -> {
synchronized (o) {
while (tick.num > 0) {
tick.num--;
System.out.println("线程 " + Thread.currentThread().getName() + "抢到了第" + (100 - tick.num) + "张票!");
try {
Thread.sleep(50);
o.notifyAll();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notifyAll();
}
System.out.println("线程" + Thread.currentThread().getName() + "done!");
deadThreads.add(Thread.currentThread());
}).start();
}
System.out.println("线程创建完毕");
try {
Thread.sleep(30000);
System.out.println(deadThreads.size());
Thread.sleep(6000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Tick {
public Integer num = 100;
}
}
@Test
public void test() {
Vector<Thread> deadThreads = new Vector<>();
Object o = new Object();
Tick tick = new Tick();
for (int i = 0; i < 1000; i++) {
new Thread(() -> {
synchronized (o) {
while (tick.num > 0) {
tick.num--;
System.out.println("线程 " + Thread.currentThread().getName() + "抢到了第" + (100 - tick.num) + "张票!");
try {
Thread.sleep(50);
o.notifyAll();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notifyAll();
}
System.out.println("线程" + Thread.currentThread().getName() + "done!");
deadThreads.add(Thread.currentThread());
}).start();
}
System.out.println("线程创建完毕");
try {
Thread.sleep(30000);
System.out.println(deadThreads.size());
Thread.sleep(6000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Tick {
public Integer num = 100;
}
}