Java Reference
In-Depth Information
Two essential operations are commonly used when dealing with threads:
sleep()
and
join()
. Both
operations throw an
InterruptedException
.
The
sleep()
method lets the thread sleep for a specii ed period, given in milliseconds. The following
code snippet puts the current thread into the sleep state for one second:
Thread.sleep(1000);
The
join()
method makes one thread wait for another thread's execution to i nish. Consider a
thread, t1, that needs a resource from another thread, t2. To make t1 wait for t2 to i nish, join t1 to
t2, as shown in the following code snippet:
t2.join();
One of the most well‐known and widely used approaches to programming asynchronously in Java
is using the
Future<V>
interface. This interface enables the use of a proxy object, which offers a
reference for the future object. Because the concurrency framework does not offer annotation‐
based support for asynchronous execution, the
Future
interface is mostly coupled with an
ExecutorService
, which is part of the concurrency framework.
The following example uses an executor service to complete a task while it returns a reference to the
Future
interface with the appropriate generic type:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> reference = executor.submit(
new Callable<String>() {
public String call() {
return "Hello!!";
}
}
);
//..
if (reference.isDone())
System.out.println(reference.get());
The
FutureTask
class is an implementation of the
Future<T>
interface, which implements the
runnable interface and can be executed directly:
FutureTask<String> reference = new FutureTask<String>(
new Callable<String>() {
public String call() {
return "Hello!!";
}
}
);
executor.execute(reference);
You can cancel this execution by calling the
cancel(boolean mayInterruptIfRunning)
method.
If the
mayInterruptIfRunning
parameter is set to
true
, calls to the method
SessionContext
.wasCancelled()
return
true
. Otherwise, a call to the
SessionContext.wasCancelled()
method
returns
false
. To check the status of cancelation, you can use the
isCancelled()
method, which
returns
tru
e if a cancelation is successful.