gpt4 book ai didi

Java在自定义方法中同时执行3个方法并从run方法中获取值

转载 作者:行者123 更新时间:2023-12-01 09:55:40 25 4
gpt4 key购买 nike

我想在Java中同时执行3个方法(显然我需要线程),并且我不想在单独的类中执行,也不想在我的主方法中执行,而是在我的自定义方法中执行。可以做到吗?

我找到了这段代码 - Execute Multiple Methods Simaltaneously Using Thread In Java并在我的示例中重复使用了最佳标记的答案,以及我拥有的参数:

private void fetchData() {

boolean t1_run = true;
boolean t2_run = true;
boolean t3_run = true;
int SLEEP_TIME = 100;//Configurable.
Thread thread1 = new Thread() {
public void run() {
while (t1_run)
{
try
{
subjects = new BeanItemContainer<KltSubject>(KltSubject.class, clijentService.getSubjecteByType(Integer.valueOf(creditor)));
Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
}
catch (Exception ex)
{
ex.printStackTrace();
}

}
}
};
Thread thread2 = new Thread() {
public void run() {
while (t2_run)
{
try
{
programs = new BeanItemContainer<Program>(Program.class, creditService.getAllPrograms());
Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
};
Thread thread3 = new Thread() {
public void run() {
while (t3_run)
{
try
{
credits = new BeanItemContainer<CreditExt>(CreditExt.class, creditService.getAllCredits());
Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

}
};
thread1.start();
thread2.start();
thread3.start();
}

现在,在我将变量放入线程中(变量名为:科目、程序和学分)之前,我可以轻松获取它们的值(您可以在上面的代码中看到这些变量在此示例中,在它们的 run 方法中,但在我的 fetchData() 方法之外定义并且可见)。

设置这样的代码并执行它后,我收到空指针异常,因为显然在线程执行后不再看到变量。在线程中执行后如何获取该值?

P.S.这段代码能否写得更优雅,代码行数更少?如果 Java 8(或 Java 7)可以做到这一点 - 请告诉我如何做到?

最佳答案

使用高级线程API:ExecutorService invokeAll()

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException

Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

示例代码:

    ExecutorService service = Executors.newFixedThreadPool(3);

List<MyCallable> futureList = new ArrayList<MyCallable>();

MyCallable1 myCallable1 = new MyCallable1(); // your first thread
MyCallable2 myCallable2 = new MyCallable2(); // your second thread
MyCallable3 myCallable1 = new MyCallable3(); // your third thread
futureList.add(myCallable1);
futureList.add(myCallable2);
futureList.add(myCallable3);

System.out.println("Start");
try{
List<Future<Long>> futures = service.invokeAll(futureList);
for(Future<Long> future : futures){
try{
System.out.println("future.isDone = " + future.isDone());
System.out.println("future: call ="+future.get());
}
catch(Exception err1){
err1.printStackTrace();
}
}
}catch(Exception err){
err.printStackTrace();
}
service.shutdown();

您可以在 article 中查看更多示例

关于Java在自定义方法中同时执行3个方法并从run方法中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37249012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com