创建线程的两种方式

首先我们需要知道什么是线程:是程序执行流的最小单元,包括就绪、阻塞和运行三种基本状态。

举个简单的例子:我们把生活中的两件事吃饭和写作业当作是两个线程,当你正在写作业的时候,爸妈叫你吃饭,你就直接去了,等吃完饭回来后再接着写作业。这就是相当于两个线程其中一个从运行状态转入就绪状态,另一个线程从就绪状态转入运行状态。

创建线程包括继承Thread类和实现Runnable接口两种方式(JDK5.0以后还包括了实现Callable等方式来实现线程,这里不做介绍,感兴趣的小伙伴可以自己查资料),下面介绍第一种创建线程的方式(通过继承Thread类):

 1 package com.test.thread;
 2 
 3 public class EasyThread extends Thread {
 4     private String name;
 5     public EasyThread(String name) {
 6         this.name=name;
 7     }
 8     //重写父类Thread中的run方法
 9     @Override
10     public void run() {
11         for (int i = 0; i <2; i++) {
12             System.out.println(name+"运行"+i);
13             try {
14                 //随机设置休眠时间
15                 sleep((int)Math.random()*10);
16             } catch (InterruptedException e) {
17                 e.printStackTrace();
18             }
19         }
20     };
21 
22     public static void main(String[] args) {
23         //创建一个线程
24         EasyThread thread1=new EasyThread("线程1");
25         //启动线程(启动线程后会执行上面的run方法)
26         thread1.start();
27         EasyThread thread2=new EasyThread("线程2");
28         thread2.start();
29     }
30 
31 }

多次运行上述代码,查看运行结果,你会发现可能每次的输出结果可能与上次相同也可能不同。因为休眠时间不同,导致运行的结果不尽相同,可以好好体会一下。下面讲述第二种创建线程的方式(实现Runnable接口):

 1 package com.test.thread;
 2 
 3 public class ImpRunnable implements Runnable {
 4     private String name;
 5 
 6     public ImpRunnable(String name) {
 7         this.name = name;
 8     }
 9 
10     // 实现接口Runnable中的run方法
11     @Override
12     public void run() {
13         for (int i = 0; i < 2; i++) {
14             System.out.println(name + "运行" + i);
15             try {
16                 // 随机设置休眠时间
17                 Thread.sleep((int) Math.random() * 10);
18             } catch (InterruptedException e) {
19                 e.printStackTrace();
20             }
21         }
22     };
23 
24     public static void main(String[] args) {
25         // 创建线程并启动(与第一种方法略有不同)
26         new Thread(new ImpRunnable("线程1")).start();
27         new Thread(new ImpRunnable("线程2")).start();
28     }
29 }

以上即为实现线程的两种常用的方式,在使用多线程(多个人共同完成同一个任务)的时候我们一般用实现Runnable接口的方式,关于两者之间具体的区别感兴趣的小伙伴可以自行查阅资料

猜你喜欢

转载自www.linuxidc.com/Linux/2016-11/136616.htm