【多线程】-实现多线程的三种方法

1.第一种是实现 Runnable,并重写run方法

 1 package com.idcos.automate.thread;
 2 
 3 import com.idcos.Application;
 4 import org.junit.runner.RunWith;
 5 import org.springframework.boot.test.SpringApplicationConfiguration;
 6 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 7 import org.springframework.test.context.web.WebAppConfiguration;
 8 
 9 /**
10  * @author GuanBin
11  * @version ThreadDemo1.java, v1 2018/5/2 下午5:43 GuanBin Exp $$
12  */
13 @RunWith(SpringJUnit4ClassRunner.class)
14 @SpringApplicationConfiguration(classes = Application.class)
15 @WebAppConfiguration
16 public class ThreadDemo1 implements Runnable {
17 
18     private Thread t;
19 
20     private String threadName;
21 
22 //    public ThreadDemo1() {
23 //
24 //    }
25 
26     public ThreadDemo1(String name) {
27         threadName = name;
28         System.out.println("Creating threadName" + threadName);
29     }
30 
31     @Override
32     public void run() {
33 
34         System.out.println("Running threadName" + threadName);
35         try {
36             for (int i = 4; i > 0; i--) {
37                 System.out.println("this thread" + i);
38                 Thread.sleep(100);
39             }
40 
41         } catch (InterruptedException e) {
42             System.out.println("This thread is Interrupted");
43         } catch (Exception e) {
44             System.out.println(e);
45         }
46 
47         System.out.println("Thread is exiting");
48 
49 
50     }
51 
52     public void start() {
53         System.out.println("Starting method name" + threadName);
54         if (t == null) {
55             t = new Thread(this, threadName);
56             t.start();
57         }
58     }
59 
60 //    @Test
61     public  static void main(String[] args) {
62         ThreadDemo1 threadDemo1 = new ThreadDemo1("testThread1");
63         threadDemo1.start();
64 
65         ThreadDemo1 threadDemo2 = new ThreadDemo1("testThread2");
66         threadDemo2.start();
67     }
68 }

输出为:

猜你喜欢

转载自www.cnblogs.com/guanbin-529/p/8984313.html