How do I add a queue to one thread from a different thread?

Kcits :

I'm trying to find a way to add a queue to one thread from a different thread.

Here's an example:

public void actionPerformed(ActionEvent e) {
    System.out.println("something happened.");
}

I believe the method actionPerformed will always execute in the EDT, but since the code inside the method isn't anything swing related, I want to schedule that to a different thread.

There's a method that allows you to schedule a task in the EDT, like:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        //insert some code that does something in EDT
    }
});

Is there any way to do the same thing, but for a normal thread?

John Kugelman :

If you have no particular preference for what background thread you want to use, try the ForkJoinPool common pool.

A static commonPool() is available and appropriate for most applications. The common pool is used by any ForkJoinTask that is not explicitly submitted to a specified pool. Using the common pool normally reduces resource usage (its threads are slowly reclaimed during periods of non-use, and reinstated upon subsequent use).

You can submit jobs many different ways. I recommend doing it via CompletableFuture which will give you a way to check on the job's status and result. All of its xxxAsync() methods submit tasks to the fork-join common pool.

If you don't care about the result, you can simply call runAsync() fire-and-forget style:

CompletableFuture.runAsync(() -> {
    System.out.println("something happened.");
});

Or if you want to compute a value off-thread you could use method chaining to take action when the job finishes:

CompletableFuture.supplyAsync(() -> {
    // expensive computation
    return result;
})
.whenComplete((result, exception) -> {
    if (exception == null) {
        System.out.println("result is " + result);
    }
    else {
        // something went wrong
        exception.printStackTrace();
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31372&siteId=1