将一个任务的不同步骤划分成子任务放到不同的线程里,这样实现的并行化并不是一个很好的办法。这些异质的子任务之间有协作关系,需要有效的机制同步——而额外的同步会对性能有一定影响,更重要的是会影响scalability。一个更好的办法是将任务划分成多个独立的同质子任务,这样子任务可以在不需要同步的情况下并行执行,性能提升的效果更明显,scalability也更强。
There is no safe way to preemptively stop a thread in Java, and therefore no safe way to preemptively stop a task. There are only cooperative mechanisms, by which the task and the code requesting cancellation follow an agreed-upon protocol.
Thread interruption is a cooperative mechanism for a thread to signal another thread that it should, at its convenience and if it feels like it, stop what it is doing and do something else.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class InterruptBeforeSleep { public static void main(String[] args) { Runnable task = new Runnable() { public void run() { System.out.println( "Running task" ); double dummy = 0.11111 ; for ( double i = 2.0 ; i < 100000000.0 ; i++) { dummy *= (i / (i- 1 )); } System.out.println( "Result is: " + dummy); System.out.println( "About to sleep" ); try { Thread.sleep(SECONDS.toMillis( 20 )); } catch (InterruptedException e) { System.out.println( "I'm interrupted" ); // The interrupt status is cleared when Thread.sleep throws InterruptedException System.out.println( "I'm interrupted? " + Thread.currentThread().isInterrupted()); } } }; Thread t = new Thread(task); t.start(); t.interrupt(); System.out.println( "Main interrupted the task thread" ); } } |
这个程序的输出:
1 2 3 4 5 6 | Main interrupted the task thread Running task Result is: 1.1110999894874712E7 About to sleep I'm interrupted I'm interrupted? false |
联系客服