`

java 并发整理

 
阅读更多

转: http://www.iteye.com/magazines/131-Java-Concurrency

 

使用Sleep方法暂停一个线程 

在Thread中有两个不同的sleep()方法,一个使用毫秒表示休眠的时间,而另一个是用纳秒。由于操作系统的限制休眠时间并不能保证十分精确。休眠周期可以被interrups所终止,我们将在后面看到这样的例子。不管在任何情况下,我们都不应该假定调用了sleep()方法就可以将一个线程暂停一个十分精确的时间周期。 

 

中断(Interrupts) 
中断是给线程的一个指示,告诉它应该停止正在做的事并去做其他事情。一个线程究竟要怎么响应中断请求取决于程序员,不过让其终止是很普遍的做法。

一个线程通过调用对被中断线程的Thread对象的interrupt()方法,发送中断信号。为了让中断机制正常工作,被中断的线程必须支持它自己的中断(即要自己处理中断) 

 

如果一个线程长时间运行而不调用会抛InterruptedException异常的方法会怎样? 那它必须周期性地调用Thread.interrupted()方法,该方法在接收到中断请求后返回true。例如: 

 

  1. for (int i = 0; i < inputs.length; i++) {  
  2.     heavyCrunch(inputs[i]);  
  3.     if (Thread.interrupted()) {  
  4.         // We've been interrupted: no more crunching.  
  5.         return;  
  6.     }  
  7. }  

 

 

 

 

 

Join
Join()方法可以让一个线程等待另一个线程执行完成。

将会使当前线程暂停执行并等待t执行完成。重载的join()方法可以让开发者自定义等待周期。然而,和sleep()方法一样join()方法依赖于操作系统的时间处理机制,你不能假定join()方法将会精确的等待你所定义的时长。 
如同sleep()方法,join()方法响应中断并在中断时抛出InterruptedException。 

 

 

一个简单的线程例子 

下面这个简单的例子将会把这一节的一些概念放到一起演示。SimpleThreads程序有两个线程组成,第一个是主线程,它从创建了一个线程并等待它执行完成。如果MessageLoop线程执行了太长时间,主线程将会将其中断。 
MessageLoop现场将会打印一系列的信息。如果中断在它打印完所有信息前发生,它将会打印一个特定的消息并退出。 

 

 

  1. public class SimpleThreads {  
  2.   
  3.     // Display a message, preceded by  
  4.     // the name of the current thread  
  5.     static void threadMessage(String message) {  
  6.         String threadName =  
  7.             Thread.currentThread().getName();  
  8.         System.out.format("%s: %s%n",  
  9.                           threadName,  
  10.                           message);  
  11.     }  
  12.   
  13.     private static class MessageLoop  
  14.         implements Runnable {  
  15.         public void run() {  
  16.             String importantInfo[] = {  
  17.                 "Mares eat oats",  
  18.                 "Does eat oats",  
  19.                 "Little lambs eat ivy",  
  20.                 "A kid will eat ivy too"  
  21.             };  
  22.             try {  
  23.                 for (int i = 0;  
  24.                      i < importantInfo.length;  
  25.                      i++) {  
  26.                     // Pause for 4 seconds  
  27.                     Thread.sleep(4000);  
  28.                     // Print a message  
  29.                     threadMessage(importantInfo[i]);  
  30.                 }  
  31.             } catch (InterruptedException e) {  
  32.                 threadMessage("I wasn't done!");  
  33.             }  
  34.         }  
  35.     }  
  36.   
  37.     public static void main(String args[])  
  38.         throws InterruptedException {  
  39.   
  40.         // Delay, in milliseconds before  
  41.         // we interrupt MessageLoop  
  42.         // thread (default one hour).  
  43.         long patience = 1000 * 60 * 60;  
  44.   
  45.         // If command line argument  
  46.         // present, gives patience  
  47.         // in seconds.  
  48.         if (args.length > 0) {  
  49.             try {  
  50.                 patience = Long.parseLong(args[0]) * 1000;  
  51.             } catch (NumberFormatException e) {  
  52.                 System.err.println("Argument must be an integer.");  
  53.                 System.exit(1);  
  54.             }  
  55.         }  
  56.   
  57.         threadMessage("Starting MessageLoop thread");  
  58.         long startTime = System.currentTimeMillis();  
  59.         Thread t = new Thread(new MessageLoop());  
  60.         t.start();  
  61.   
  62.         threadMessage("Waiting for MessageLoop thread to finish");  
  63.         // loop until MessageLoop  
  64.         // thread exits  
  65.         while (t.isAlive()) {  
  66.             threadMessage("Still waiting...");  
  67.             // Wait maximum of 1 second  
  68.             // for MessageLoop thread  
  69.             // to finish.  
  70.             t.join(1000);  
  71.             if (((System.currentTimeMillis() - startTime) > patience)  
  72.                   && t.isAlive()) {  
  73.                 threadMessage("Tired of waiting!");  
  74.                 t.interrupt();  
  75.                 // Shouldn't be long now  
  76.                 // -- wait indefinitely  
  77.                 t.join();  
  78.             }  
  79.         }  
  80.         threadMessage("Finally!");  
  81.     }  
  82. }  

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics