Java 访问executor服务中的特定线程
我目前正试图模拟一家制造飞机的工厂,该工厂有10个机器人(线程),将在对象(飞机)上工作,直到没有更多的机器人。为此,我使用了一个固定大小为10个线程的Java 访问executor服务中的特定线程,java,concurrency,executorservice,Java,Concurrency,Executorservice,我目前正试图模拟一家制造飞机的工厂,该工厂有10个机器人(线程),将在对象(飞机)上工作,直到没有更多的机器人。为此,我使用了一个固定大小为10个线程的ExecutorService。机器人本身是一个扩展线程的自定义类,为了阻止其run()方法立即完成,我让机器人有一个名为active的布尔值,我将其设置为true,如下所示: public void run() { while (this.active) { while (this.workingAirc
ExecutorService
。机器人本身是一个扩展线程的自定义类,为了阻止其run()
方法立即完成,我让机器人有一个名为active的布尔值,我将其设置为true,如下所示:
public void run() {
while (this.active) {
while (this.workingAircraft == null) {
// System.out.println(this.getID() + " has no aircraft to work on, reporting to operator");
try {
this.workingAircraft = this.op.getAircraft(this.id);
// System.out.println(this.toString() + " has recieved aircraft" + this.workingAircraft.getID());
} catch (Exception ex) {
// System.out.println("Operator is busy");
try {
this.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(this.workingAircraft !=null) {
//System.out.println(this.toString() + " is working on Aircraft " + this.workingAircraft.getID());
while (this.installAmount > 0) {
// System.out.println(" " + this.toString() + " :*clank* *clank*");
this.installAmount--;
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
// System.out.println(this.getID() + " has finished working on aircraft");
this.returnToQueue();
this.workingAircraft = null;
}
}
}
机器人线程与操作员
类通信。此类检查arrayBlockingQueue中是否有属于工厂
类的飞机。如果有,根据一些逻辑将其分配给机器人线程:
public synchronized Aircraft getAircraft(int id) {
Aircraft a = this.factory.getAirCrafts().poll();
if(a.getPartsNeeded().contains(id)){
this.leaveWaiting(id); // remove the robot from the waitingList
return a; //only give a robot an aircraft if it has the desired parts
}
this.factory.getAirCrafts().add(a);
return null;
}
我将机器人提交给执行者服务,如下所示:
for (int i = 0; i < 10; i++) {
final Robot r = new Robot(this, i, operator);
//robots.add(r);
runningRobots.add(threadPool.submit(r));
}
for(int i=0;i<10;i++){
最终机器人r=新机器人(该,i,操作员);
//添加(r);
runningRobots.add(threadPool.submit(r));
}
我还尝试将机器人添加到arrayList中,并以这种方式访问它们,但是,在arrayList中为机器人调用方法似乎对executor服务中的线程没有影响
我现在的主要问题是这个。有固定数量的10个机器人线程,但是,运行程序的用户设置飞机的初始数量。这意味着我不能在(!queue.isEmpty()){//robot thread do work}时简单地执行之类的操作,因为队列本身可能是空的,但这并不意味着程序中的其他机器人已经完成了其逻辑的运行
在运行时,是否有任何方法可以从executor服务访问这些robot对象,以便我可以在一段时间或条件后将其活动字段设置为false?我曾经尝试将它们提交到执行器服务,然后尝试将它们添加到arrayList中,但我对arrayList中的robot对象所做的任何操作似乎都不会影响线程池中的线程。没有从执行器获取特定线程的默认设置。像您这样的自定义实现是一个不错的选择。分享您如何将线程添加到列表以及如何访问它们的一些代码。也许有什么事,好吧,我会的!谢谢。在那里添加了更多信息!没有从执行器获取特定线程的默认设置。像您这样的自定义实现是一个不错的选择。分享您如何将线程添加到列表以及如何访问它们的一些代码。也许有什么事,好吧,我会的!谢谢。在那里添加了更多信息!