JAVA创建线程的三种方式
Java 创建线程主要有三种方式:继承Thread类,实现Runnable接口,实现Callable接口。
一 继承Thread类创建线程
1 定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务。因此把run()方法称为执行体。
2 创建Thread子类的实例,即创建了线程对象。
3 调用线程对象的start()方法来启动该线程。
1 //继承Thread类 2 public class MyThread extends Thread{ 3 int i = 0; 4 //重写run方法 5 public void run() 6 { 7 for(;i<50;i++){ 8 System.out.println(getName()+" "+i); 9 10 } 11 } 12 13 public static void main(String[] args) 14 { 15 for(int i = 0;i< 50;i++) 16 { 17 System.out.println(Thread.currentThread().getName()+" : "+i); 18 if(i==10) 19 { 20 new MyThread ().start(); 22 } 23 } 24 } 26 }
二 实现Runnable接口创建线程类
1 定义runnable接口的实现类,并重写该接口的run()方法,这个run()方法和Thread中的run()方法一样是线程的执行体
2 创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象,该Thread对象才是真正的线程对象。
3 调用线程对象的start()方法来启动该线程。
1 package com.thread; 2 3 public class MyThread2 implements Runnable 4 { 5 6 private int i; 7 public void run() //重写run方法 8 { 9 for(i = 0;i <100;i++) 10 { 11 System.out.println(Thread.currentThread().getName()+" "+i); 12 } 13 } 14 public static void main(String[] args) 15 { 16 for(int i = 0;i < 100;i++) 17 { 18 System.out.println(Thread.currentThread().getName()+" "+i); 19 if(i==20) 20 { 21 MyThread2 mt = new MyThread2 (); 22 new Thread(mt ,"线程").start(); 23 } 24 } 25 26 } 27 28 } 29
三 通过Callable和Future创建线程
1 创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
2 创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
3 使用FutureTask对象作为Thread对象的target创建并启动新线程。
4 调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
1 package com.thread; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.FutureTask; 6 7 public class CallableThreadTest implements Callable<Integer> 8 { 9 10 public static void main(String[] args) 11 { 12 CallableThreadTest ctt = new CallableThreadTest(); 13 FutureTask<Integer> ft = new FutureTask<>(ctt); 14 for(int i = 0;i < 100;i++) 15 { 16 System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i); 17 if(i==20) 18 { 19 new Thread(ft,"有返回值的线程").start(); 20 } 21 } 22 try 23 { 24 System.out.println("子线程的返回值:"+ft.get()); 25 } catch (InterruptedException e) 26 { 27 e.printStackTrace(); 28 } catch (ExecutionException e) 29 { 30 e.printStackTrace(); 31 } 32 33 } 34 35 @Override 36 public Integer call() throws Exception 37 { 38 int i = 0; 39 for(;i<100;i++) 40 { 41 System.out.println(Thread.currentThread().getName()+" "+i); 42 } 43 return i; 44 } 45 46 }
几种方式对比
采用实现Runnable、Callable接口的方式创见多线程时
优势:
线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。
在这种方式下,多个线程可以共享同一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU、代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。
劣势:
编程稍微复杂,如果要访问当前线程,则必须使用Thread.currentThread()方法。
使用继承Thread类的方式创建多线程时
优势:
编写简单,如果需要访问当前线程,则无需使用Thread.currentThread()方法,直接使用this即可获得当前线程。
劣势:
线程类已经继承了Thread类,所以不能再继承其他父类。

浙公网安备 33010602011771号