创建线程有三种方式:
1.继承Thread类
2.实现Runnable接口
3.使用Callable和Future创建线程
三种方式详解如下:
---------------------------------------------------------------------------
1.继承Thread类创建线程类
(1).重写run()方法,run()方法即是线程的执行体
(2).实例化线程类
(3).调用start()方法,启动线程
代码示例:
public class MyThread extends Thread { int i = 0; public void run() { for(; i <= 50;i++) { System.out.println(getName() + i); } } public static void main(String args[]) { for(int i=0;i <= 50;i++) { if(i == 10) { MyThread myThread = new MyThread(); myThread.start(); } } } }
2.创建实现Runnable接口的线程类:
(1)重写run()方法,run()方法是线程的执行体
(2)创建线程类的实例,并以该实例为对象创建Thread类的实例,Thread类对象才是真正的线程对象
(3)通过Thread对象调用start()方法,启动线程
代码示例:
public class MyRunnable implements Runnable { private int i; @Override public void run() { // TODO Auto-generated method stub for(int i=0; i<=50;i++) { System.out.println(Thread.currentThread().getName() + i); } } public static void main(String args[]) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable, "new Thread"); thread.start(); } }
3.通过Callable和Future创建线程:
(1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
(2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值
(3)使用FutureTask对象作为Thread对象的参数创建并启动新线程
(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
代码示例:
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class CallableThread implements Callable<Integer> { @Override public Integer call() throws Exception { // TODO Auto-generated method stub int i = 0; for(;i<=50;i++) { System.out.println(Thread.currentThread().getName() + i); } return i; } public static void main(String args[]) { CallableThread ct = new CallableThread(); FutureTask<Integer> ft = new FutureTask<>(ct); for(int i=0;i <= 50;i++) { new Thread(ft,"返回线程").start(); } try { System.out.println("线程的返回值:" + ft.get()); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
通过以上的代码实例,我们可以看到:
基于Runnablehe和Callable接口实现的线程类比较灵活,可继承其他类,适合多个线程处理同一个资源的情况,但与此同时代码较复杂,访问当前线程时要使用Thread.currentThread()方法。
而继承Thread实现的线程类在访问当前线程时只使用this即可访问,但因为继承了Thread类,不能再继承其他类