Java多线程实践
1.实现Runnable接口
1 import java.util.Random;
2
3
4 public class PrintTask implements Runnable{
5 private final int sleepTime;
6 private final String taskName;
7 private final static Random generator = new Random();
8
9
10 public PrintTask(String name) {
11 taskName = name;
12 sleepTime = generator.nextInt(5000);
13 }
14
15 @Override
16 public void run() {
17 try {
18 System.out.printf("%s going to Sleep for %d milliseconds.\n",
19 taskName, sleepTime);
20 Thread.sleep(sleepTime);
21 } catch (InterruptedException e) {
22 System.out.printf("%s %s\n", taskName, "terminated prematurely" +
23 " due to interruption");
24 }
25 System.out.printf("%s done sleeping\n", taskName);
26 }
27
28 }
2.使用ExecutorService管理执行PrintTask的线程
1 import java.util.Random;
2
3
4 public class PrintTask implements Runnable{
5 private final int sleepTime;
6 private final String taskName;
7 private final static Random generator = new Random();
8
9
10 public PrintTask(String name) {
11 taskName = name;
12 sleepTime = generator.nextInt(5000);
13 }
14
15 @Override
16 public void run() {
17 try {
18 System.out.printf("%s going to Sleep for %d milliseconds.\n",
19 taskName, sleepTime);
20 Thread.sleep(sleepTime);
21 } catch (InterruptedException e) {
22 System.out.printf("%s %s\n", taskName, "terminated prematurely" +
23 " due to interruption");
24 }
25 System.out.printf("%s done sleeping\n", taskName);
26 }
27
28 }
3.执行结果

可以看到,由于每个任务随机休眠时间不同,执行结束的顺序是不同的。