标签: executorservice

如何知道提交给执行人的任务是否引发异常?

如果我在a中运行一个线程,有ExecutorService没有办法知道这个线程在开始执行时没有抛出异常?

java multithreading executorservice executor

2
推荐指数
1
解决办法
3103
查看次数

即使任务尚未完成,如何停止执行程序服务线程?

我使用 Executor Service 启动了一些线程,以便从网络获取一些文件。我希望线程在一段时间后停止执行,即使它们的 run 方法尚未完成。怎么做?甚至执行器的 shutdown() 和awaitTermination(...) 方法也不起作用。

java multithreading executorservice

2
推荐指数
1
解决办法
1332
查看次数

Executor框架和消息队列(如JMS)之间的区别

消息队列主要用于在服务器上执行异步任务,我最近阅读了有关Executor框架的内容,它也执行相同的操作,生成并管理线程以执行异步任务.谁能告诉我两者之间的区别?

java asynchronous message-queue executorservice

2
推荐指数
1
解决办法
744
查看次数

如何在 Java 中实现非阻塞 Futures

Java Future 对象用于获取由并行线程(Executors)执行的异步计算的结果。我们调用 Future.get() 方法并等待结果准备就绪。此示例显示了从 Future 检索结果的非阻塞方式。java-implement-java-non-blocking-futures

NonBlockingExecutor executor = new NonBlockingExecutor(Executors.newSingleThreadExecutor());

NonBlockingFuture<Integer> future = executor.submitNonBlocking(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName);
                //print -> pool-1-thread-1
                return 1;
            }
});

future.setHandler(new FutureHandler<Integer>() {

       @Override
       public void onSuccess(Integer value) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName);
            //print -> pool-1-thread-1
       }

       @Override
       public void onFailure(Throwable e) {
            System.out.println(e.getMessage());
       }
 });

 Thread.sleep(50000);
Run Code Online (Sandbox Code Playgroud)

在此 onSuccess() 方法在并行执行完成后被调用。问题是 onSuccess() 方法没有在主线程上运行。我想在主线程上执行 onSuccess() 方法。我怎样才能解决这个问题。谢谢

java multithreading future nonblocking executorservice

2
推荐指数
2
解决办法
1万
查看次数

当executor遇到Thread.sleep时,为什么线程没有休眠就结束或者抛出InterruptedException?

我不知道为什么 junit 有以下行为:

当我将一个线程提交到执行程序(fixedThreadPool 或其他),而该线程具有睡眠行为(Thread.sleep())时,我发现该线程立即结束!没有睡眠,没有中断的异常。

我想知道为什么?

(我知道下面的设计不好,但我只是想描述一下上面的问题)

@Test
public void executorPoolTest(){
    ExecutorService cachedThreadPool = 
            Executors.newFixedThreadPool(10);
    //Executors.newCachedThreadPool();  
    for (int i = 0; i < 1000; i++) {  
        final int index = i;  
        cachedThreadPool.execute(new Runnable() {  
            public void run() {  
                System.out.println(index);
                try {  
                    Thread.sleep( 5000); 
                    System.out.println(index+"_");
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
    }
    //no matter whether you call shutdown, the above program will ends quickly.
    cachedThreadPool.shutdown();

}
Run Code Online (Sandbox Code Playgroud)

上面的程序没有打印任何数字+“_”,很奇怪。但是,如果上述方法在主方法中运行(我的意思是:public static void main(String[] args)),则行为正常,线程将休眠并且可以打印“_”。

我想知道为什么?junit框架发生了什么?如果是这样,我不能使用 junit 来测试执行器涉及的方法吗?

junit版本是4.12。

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId> …
Run Code Online (Sandbox Code Playgroud)

java junit multithreading executorservice thread-sleep

2
推荐指数
1
解决办法
2687
查看次数

关闭 ScheduledExecutorService 是否安全?

我正在实现一项服务,该服务执行一些由此处模拟的长时间运行的任务Thread.sleep(10000)。当我 ctrl+c 执行时,我从未得到InterruptedException我所期望的结果。我想知道为什么。

package simple;

import my.util.Now;
import io.dropwizard.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class EmailSender implements Managed {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailSender.class);
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);

    // Constructor
    public EmailSender() {}

    @Override
    public void start() {
        LOGGER.info("Starting email sender thread: {}", Thread.currentThread().getName());
        Runnable task = () -> {
            LOGGER.info("Running: {} in thread: {}", Now.now(), Thread.currentThread().getName());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ie) {
                LOGGER.error("Task is being …
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice

2
推荐指数
1
解决办法
3593
查看次数

使用 ExecutorService.invokeAll 时,即使发生异常,也有办法获取所有响应

在java中,我想运行多个线程并从所有线程中获取响应。

我遇到的问题是,如果当我执行 String temp = r.get() 时其中一个线程抛出异常,它就会陷入捕获并且不会给我剩余线程的响应。

有没有一种方法可以处理所有响应,而不管单个线程是否抛出异常?

我的测试代码是

    ExecutorService es = Executors.newFixedThreadPool(2);
    List<CallTest> callList = new ArrayList<>();

    callList.add(new CallTest(1));
    callList.add(new CallTest(2));
    callList.add(new CallTest(3));
    callList.add(new CallTest(4));


    try {
        List<Future<String>> returns = es.invokeAll(callList);
        for (Future<String> r : returns) {
            String temp = r.get();
            System.out.println("returned " + temp);

        }
    } catch (InterruptedException e) {
        System.out.println("Interrupted Exception catch");
        e.printStackTrace();
    } catch (ExecutionException e) {
        System.out.println("Execution Exception catch");
        e.printStackTrace();

    }
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice

2
推荐指数
1
解决办法
4603
查看次数

如何在 Java 中并行处理对象列表

我在 Java 中有一个对象列表,例如 List 中的数千个对象,我正在为每个对象迭代 List 并进行进一步处理。每个对象都在进行相同的处理。这种顺序方法需要很多时间来处理,所以我想用 Java 中的并行处理来实现。我检查了 Java 中的执行程序框架,但我陷入了困境。

我想了一种方法来实现我的要求。

我想实现一些固定数量的最小对象将由每个线程处理,以便每个线程以快速的方式完成其工作和处理对象。我怎样才能做到这一点?或者,如果有任何其他方法可以实现我的要求,请分享。

例如:

列表对象 = new List();

For(Object object : objects) { //对所有的Object做一些通用的操作

}

java concurrency multithreading multiprocessing executorservice

2
推荐指数
2
解决办法
1万
查看次数

Thread.join()在ExecutorService执行Thread时不起作用

这是我的代码:

public static void main(String[] args) {
        System.out.println("program started");
        ExecutorService executor = Executors.newCachedThreadPool();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread finished");
            }
        });
        executor.execute(thread);
        try {
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("thread joined");

    }
Run Code Online (Sandbox Code Playgroud)

当我如上所示启动我的线程时,thread.join()它不起作用,它不会等待线程完成.我需要通过ExecutorService执行我的Thread,并等待该Thread完成.但是我的代码效果不好.谁能帮我?

为什么我不使用Future而不是Thread

因为有时我需要中断我的线程并等待线程完成.但是当我取消一个Future时,future.get()得到一个Exception并且不等待它的Thread完成.

如果我的句子的语法不正确,我会提前道歉.因为我不会说英语.

java multithreading executorservice

2
推荐指数
2
解决办法
269
查看次数

Executor 执行两次

我正在尝试同时运行 2 个线程以实现多线程,并且我的程序正在运行,但我怀疑为什么我的程序打印到标准输出两次。

这是我的代码库:

public class SimpleExec {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        CountDownLatch countDownLatch6 = new CountDownLatch(5);
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        System.out.println("start" + LocalDateTime.now());
        executorService.execute(new MyThread("first ", countDownLatch));
        executorService.execute(new MyThread("Second", countDownLatch6));

        try {
            countDownLatch.await();
            countDownLatch6.await();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
        System.out.println("end" + LocalDateTime.now());
        executorService.shutdown();

    }
}

class MyThread implements Runnable {
    String name;
    CountDownLatch cdl;

    public MyThread(String name, CountDownLatch cdl) {
        this.cdl = cdl;
        this.name = name;
        new Thread(this).start();
    }

    public …
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice

2
推荐指数
1
解决办法
1257
查看次数