我正在使用spring和java。我有以下配置。
应用程序上下文.xml
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="waitForTasksToCompleteOnShutdown" value="true" />
</bean>
打印任务.java
public class PrintTask implements Runnable{
String name;
public PrintTask(String name){
this.name = name;
}
@Override
public void run() {
Map<String, String> map = new HashMap<String, String>();
map.put(name + " is running", name + " is running");
Container.containerMap.put(this, map);
System.out.println(name + " is running");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " is running");
}
}
PrintTaskTest.java
public class PrintTaskTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
taskExecutor.execute(new PrintTask("Thread 1"));
taskExecutor.execute(new PrintTask("Thread 2"));
taskExecutor.execute(new PrintTask("Thread 3"));
taskExecutor.execute(new PrintTask("Thread 4"));
taskExecutor.execute(new PrintTask("Thread 5"));
//check active thread, if zero then shut down the thread pool
for (;;) {
int count = taskExecutor.getActiveCount();
System.out.println("Active Threads : " + count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 0) {
taskExecutor.shutdown();
break;
}
}
}
}
容器.java
public class Container {
public static Map<PrintTask, Map<String,String>> containerMap = new HashMap<PrintTask, Map<String,String>>();
}
我的要求是:
我有几个线程调用相同的逻辑。在我的示例中,PrintTask 被 5 个线程调用。每当调用逻辑时,我都必须将值作为键值对存储在映射中。
Key = current Theread object
value = some Map
再次,当需要时,我可以传递当前线程并从地图中获取其值。
我做得对吗?
谢谢!