2.终止线程
在1.0中,可以用stop方法来终止,但是现在这种方法已经被禁用了,改用interrupt方法。interrupt方法并不是强制终止线程,它只能设置线程的interrupted状态,而在线程中一般使用一下方式:
while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
而被block的线程在被调用interrupt时会产生InterruptException,此时是否终止线程由本线程自己决定。程序的一般形式是:
public void run()
{
try
{
. . .
while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
}
catch(InterruptedException e)
{
// thread was interrupted during sleep or wait
}
finally
{
cleanup, if required
}
// exiting the run method terminates the thread
}
使用lock的基本形式是:
myLock.lock(); // a ReentrantLock object
try
{
critical section
}
finally
{
myLock.unlock(); // make sure the lock is unlocked even if an exception is thrown
}
8. Callables and Futures
实现多线程时一般用的是Runnable接口,但是他有一个问题就是他没有参数和返回值,所以当执行一个线程需要返回一个值的时候就不是很方便了。Callable接口和Runnable差不多,但是他提供了参数和返回值:
public interface Callable
{
V call() throws Exception;
}
而Future接口可以保留异步执行的值:
public interface Future
{
V get() throws . . .;
V get(long timeout, TimeUnit unit) throws . . .;
void cancel(boolean mayInterrupt);
boolean isCancelled();
boolean isDone();
}
FutureTask可以很方便的把Callable转换成Future和Runnable:
Callable myComputation = . . .;
FutureTask task = new FutureTask(myComputation);
Thread t = new Thread(task); // it's a Runnable
t.start();
. . .
Integer result = task.get(); // it's a Future
9.用Executors创建线程池
用线程池有两个好处:1. 减少创建线程的开销。2. 控制线程的数量。
EXecutors提供了一些方法可以很方便的创建线程池:
newCachedThreadPool
New threads are created as needed; idle threads are kept for 60 seconds.
newFixedThreadPool
The pool contains a fixed set of threads; idle threads are kept indefinitely.
newSingleThreadExecutor
A "pool" with a single thread that executes the submitted tasks sequentially.
newScheduledThreadPool
A fixed-thread pool for scheduled execution.
newSingleThreadScheduledExecutor
A single-thread "pool" for scheduled execution.