相关疑难解决方法(0)

为什么ExecutorService不调用UncaughtExceptionHandler?

我偶然发现了一个问题,可归纳如下:

当我手动创建线程(即通过实例化java.lang.Thread)时,UncaughtExceptionHandler适当地调用.但是,当我使用ExecutorService带有ThreadFactory处理程序时,ommited.我错过了什么?

public class ThreadStudy {

private static final int THREAD_POOL_SIZE = 1;

public static void main(String[] args) {

    // create uncaught exception handler

    final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            synchronized (this) {
                System.err.println("Uncaught exception in thread '" + t.getName() + "': " + e.getMessage());
            }
        }
    };

    // create thread factory

    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) …
Run Code Online (Sandbox Code Playgroud)

java multithreading

55
推荐指数
5
解决办法
3万
查看次数

Java中此代码中的ExecutorService.submit和ExecutorService.execute有什么区别?

我正在学习用来ExectorService汇集threads和发送任务.我有一个简单的程序如下

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


class Processor implements Runnable {

    private int id;

    public Processor(int id) {
        this.id = id;
    }

    public void run() {
        System.out.println("Starting: " + id);

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.out.println("sorry, being interupted, good bye!");
            System.out.println("Interrupted "+Thread.currentThread().getName());
            e.printStackTrace();    
        }

        System.out.println("Completed: " + id);
    }
}


public class ExecutorExample {

    public static void main(String[] args) {
        Boolean isCompleted=false;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        for(int i=0; i<5; i++) {
            executor.execute(new …
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice threadpool

53
推荐指数
6
解决办法
7万
查看次数

使用ThreadPoolExecutor提交和执行方法有什么区别

我发现有两种方法(提交和执行)将Runnable添加到线程池中,有什么区别?

java multithreading

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

从Java ExecutorService捕获线程异常

我正在研究用于并行计算JavaSeis.org的软件开发框架.我需要一个强大的机制来报告线程异常.在开发过程中,了解异常的来源具有很高的价值,因此我想在过度报告方面犯错误.我也希望能够在线程中处理Junit4测试.方法是否合理或有更好的方法吗?

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override …
Run Code Online (Sandbox Code Playgroud)

java multithreading exception

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

Java:如何中断/停止线程?

我试图阻止一个线程,但我不能这样做:

public class Middleware {

public void read() {
    try {
        socket = new Socket("192.168.1.8", 2001);

        // code .. 

        Scan scan = new Scan();
        thread = new Thread(scan);
        thread.start();

    } catch (UnknownHostException ex) {
        ex.printStackTrace();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

class Scan extends Thread {

    public void run() {

        while (true) {
            try {
            // my code goes here

            } catch (IOException ex) {
                thread.currentThread().interrupt();
            }
        }
    }
}

public void stop() {
    Thread.currentThread().interrupt();
}

// get …
Run Code Online (Sandbox Code Playgroud)

java multithreading

15
推荐指数
5
解决办法
6万
查看次数

线程池执行时抛出异常时线程会发生什么?

线程池执行时抛出异常时线程会发生什么?

它会终止并被垃圾收集吗?

背景故事: 我正在使用a ScheduledThreadPoolExecutor不时地运行任务,而且它也被Netty使用.现在,使用此应用程序的客户告诉我,他们有时会注意到一堆客户端随机断开连接,每次发生这种情况时,都会记录来自单独的非网络相关任务的堆栈跟踪.我的假设是线程被中断并且垃圾被收集,因此Netty丢失了对线程的任何引用并断开了分配的tcp客户端.

java multithreading threadpool

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

"由于故障导致的线程终止"是指什么?

javadoc ExecutorService有时指的是Thread因"失败"而终止的情况.但是,目前尚不清楚这是指什么样的失败.

例如,单线程执行程序文档说明了这一点

如果这个单线程由于在关闭之前执行期间的故障而终止,那么如果需要执行后续任务,则新线程将取代它

我原以为这种情况可能发生在Exception或者a RuntimeException的情况下,但似乎并非如此.运行以下代码似乎给出了相同的线程名称和线程ID.

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
  System.out.println("Hello from " + Thread.currentThread().getName()+ " " + Thread.currentThread().getId());
  throw new NullPointerException("Test");
});

executor.submit(() -> {
  System.out.println("Hello 2 from " + Thread.currentThread().getName() + " " + Thread.currentThread().getId());
});
Run Code Online (Sandbox Code Playgroud)

此代码的输出是:

Hello from pool-1-thread-1 12
Hello 2 from pool-1-thread-1 12
Run Code Online (Sandbox Code Playgroud)

似乎即使在这种情况下,同一个线程也被重用NullPointerException.

那么Javadoc指的是什么样的"失败"?

java multithreading executorservice

6
推荐指数
1
解决办法
293
查看次数

提交和等待ExecutorService终止的正确方法

我正在学习如何使用Java在Java中使用线程池ExecutorService,这是我正在处理的示例:

public class Example {
    static class WorkerThread implements Runnable {
        private String command;

        public WorkerThread(String s) {
            this.command = s;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
            processCommand();
            System.out.println(Thread.currentThread().getName() + " End.");
        }

        private void processCommand() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return this.command;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(5); …
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice threadpool

5
推荐指数
1
解决办法
4937
查看次数