java面试题网

普通会员

216

帖子

75

回复

160

积分

楼主
发表于 2019-05-05 14:21:31 | 查看: 171| 回复: 0

创建n多个线程,如何保证这些线程同时启动?看清,是“同时”。

用一个for循环创建线程对象,同时调用wait()方法,让所有线程等待;直到最后一个线程也准备就绪后,调用notifyAll(), 同时启动所有线程。

比如:给你n个赛车,让他们都在起跑线上就绪后,同时出发,Java多线程如何写代码?

思路是,来一辆赛车就加上一把锁,并修改对应的操作数,如果没有全部就绪就等待,并释放锁,直到最后一辆赛车到场后唤醒所有的赛车线程。代码参考如下:
public class CarCompetion {
// 参赛赛车的数量
protected final int totalCarNum = 10;
// 当前在起跑线的赛车数量
protected int nowCarNum = 0;
}
public class Car implements Runnable{
private int carNum;
private CarCompetion competion = null;
public Car(int carNum, CarCompetion competion) {
this.carNum = carNum;
this.competion = competion;
}
@Override
public void run() {
synchronized (competion) {
competion.nowCarNum++;
while (competion.nowCarNum < competion.totalCarNum) {
try {
competion.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
competion.notifyAll();
}
startCar();
}
private void startCar() {
System.out.println("Car num " + this.carNum + " start to run.");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Car num " + this.carNum + " get to the finish line.");
}
}

public static void main(String[] args) {
CarCompetion carCompetion = new CarCompetion();
final ExecutorService carPool =
Executors.newFixedThreadPool(carCompetion.totalCarNum);
for (int i = 0; i < carCompetion.totalCarNum; i++) {
carPool.execute(new Car(i, carCompetion));

}


您需要登录后才可以回帖 登录 | 立即注册

java面试题网无聊看看网与java建站系统提供技术支持V2.1 网站地图 © 2016-2018