Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use </p> <pre><code>Executor executor = Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { anotherMethod(); } }); // this is called automatically when the object is gc-ed, // but you should not rely on this, hence the explicit call executor.shutdown(); </code></pre> <p>To quote Effective Java:</p> <blockquote> <p>Not only should you refrain from writing your own work queues, but you should generally refrain from working directly with threads. The key abstraction is no longer Thread, which served as both the unit of work and the mechanism for executing it. Now the unit of work and mechanism are separate. The key abstraction is the unit of work, which is called a task. There are two kinds of tasks: Runnable and its close cousin, Callable (which is like Runnable, except that it returns a value). The general mechanism for executing tasks is the executor ser- vice. If you think in terms of tasks and let an executor service execute them for you, you gain great flexibility in terms of selecting appropriate execution policies. In essence, the Executor Framework does for execution what the Collections Framework did for aggregation.</p> </blockquote> <p>Note that you'd better create your executor only once, store it in an instance field and reuse it (and shut it down afterwards)</p> <p>If you are running in JavaEE 6 or spring, you can annotate your <code>anotherMethod()</code> with <code>@Asynchronous</code> and the container will start a new thread for you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload