多线程Java区分可运行线程类型
上下文:
我有一个任务,我必须让“领导者”和“追随者”同时配合,以便合作共舞。有好几个舞蹈,好几个领袖,好几个追随者。其基本思想是,一个领导者一次只能要求一个追随者跳一支舞。然而,许多领导者可以同时向不同的追随者索要舞蹈。追随者只能接受或拒绝领导者的请求。他们不能提出自己的要求。每个舞蹈可以而且应该有多对领队-跟随者,但同一个领队在一个给定的舞蹈中不应该有超过一个跟随者,并且一个跟随者不应该同意在一个给定的舞蹈中与超过一个领队跳舞
尝试的解决方案:
我这样做的方式是创建一个Leader
和Follower
类,它们都实现了Runnable
然后在我的主Dance
类的main()
方法中,我产生了Leader
和Follower
线程。
我存储匹配项的方式是使用ConcurrentHashMap<String, Integer>
。此CHM存在于两个Leader的类定义中。java和Follower。JAVACHM将舞蹈的名称存储为一个键,以及同意舞蹈的跟随者的threadID(在Leader.java中)
问题: 我对Leader线程和Follower线程如何相互通信感到困惑,特别是因为我拥有的关于线程的唯一标识信息是线程的ID。这些线程中的每个线程分别包含Leader和Follower类的实例,但我不确定如何让这些对象“对话”
例如,领导者如何将他们的CHM“发送”到Follower类,以便Follower的实例能够适当地回复它
代码: 跳舞。java:
public class Dance{
public static void main(String[] args){
int nLeaders = 0;
int mFollowers = 0;
// Take in program args from command line and pass them to local vars so we can store them
try {
nLeaders = Integer.parseInt(args[0]);
mFollowers = Integer.parseInt(args[1]);
}
catch (Exception e){
System.out.println("Please make sure you have provided valid args for N and M");
}
// Spawn the specified number of leader/follower threads according to args
for(int i = 1; i <= nLeaders; ++i){
Thread spawnedLeaderThread = new Thread(new Leader()); // creates instances of our Leader class as threads
spawnedLeaderThread.start(); // Starts all the threads we just created in the loop
}
for(int i = 1; i <= mFollowers; ++i){
Thread spawnedFollowerThread = new Thread(new Follower()); // creates instances of our Leader class as threads
spawnedFollowerThread.start(); // Starts all the threads we just created in the loop
}
}
}
领导。java:
import java.util.concurrent.ConcurrentHashMap;
class Leader implements Runnable{
ConcurrentHashMap<String, Integer> leaderCHM = new ConcurrentHashMap();
// K,V = String for Dance Type (D1, D2, etc.), Integer for Follower threadID
public Leader(){
leaderDC.put("D1", -1); // Initialize all the keys (dance types) with -1 (match not found yet) to be later set according to matched leaders
leaderDC.put("D2", -1);
leaderDC.put("D3", -1);
leaderDC.put("D4", -1);
leaderDC.put("D5", -1);
leaderDC.put("D6", -1);
leaderDC.put("D7", -1);
leaderDC.put("D8", -1);
}
@Override
public void run(){
try{
String threadName = Thread.currentThread().getName();
System.out.println("Spawning a Leader Thread w/ID of " + Thread.currentThread().getId() + " and name of " + threadName); // Prints out the id of this current thread
}
catch(Exception e){
System.out.println("Caught a thread exception in Leader.java");
}
}
}
追随者。java
class Follower implements Runnable{
@Override
public void run() {
try{
String threadName = Thread.currentThread().getName();
System.out.println("Spawning a Follower Thread w/ID of " + Thread.currentThread().getId() + " and name of " + threadName); // Prints out the id of this current thread
}
catch(Exception e){
System.out.println("Caught a thread exception in Follower.java");
}
}
}
共 (0) 个答案