技术开发 频道

Java并发编程:线程

  下面举例总结本节所说明的一些概念。SimpleThreads由两个线程组成,第一个是主线程,主线程使用一个Runnable对象MessageLoop创建一个新的线程,并等待该线程结束。如果MessageLoop线程耗时太长,那么主线程将强制中断该线程。

  MessageLoop线程打印出一系列的消息,如果被中断,则打印消息并退出:

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