Java 建立线程的方式一共有 四种方式:html
1.继承 Thread 类java
2. 实现 Runnable 接口ide
3. ExecuteService、Callable<Class>、Future 有返回值线程线程
4. 线程池方式(http://www.javashuo.com/article/p-zpxgejsk-a.html)code
1、继承 Thread 类,建立线程类htm
(1)定义 Thread 类的子类,并重写该类的 run 方法,该run方法的方法体就表明了线程要完成的任务。所以把 run() 方法称为执行体。对象
(2)建立 Thread 子类的实例,即建立了线程对象。blog
(3)调用线程对象的 start() 方法来启动该线程。继承
package jichu_0; public class ForWays_Thread extends Thread { int i = 0; // 重写run方法,run方法的方法体就是现场执行体 public void run() { for (; i < 100; i++) { System.out.println(getName() + " " + i); } } public static void main(String[] args) { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " : " + i); if (i == 20) { new ForWays_Thread().start(); new ForWays_Thread().start(); } } } } Thread.currentThread()方法返回当前正在执行的线程对象。GetName()方法返回调用该方法的线程的名字。
2、经过 Runnable 接口,建立线程类接口
(1)定义 runnable 接口的实现类,并重写该接口的 run() 方法,该 run() 方法的方法体一样是该线程的线程执行体。
(2)建立 Runnable 实现类的实例,并依此实例做为 Thread 的 target 来建立 Thread 对象,该 Thread 对象才是真正的线程对象。
(3)调用线程对象的 start() 方法来启动该线程。
package jichu_0; public class ForWays_Runnable implements Runnable { private int i; public void run() { for (i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } } public static void main(String[] args) { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " " + i); if (i == 20) { ForWays_Runnable rtt = new ForWays_Runnable(); new Thread(rtt, "新线程1").start(); new Thread(rtt, "新线程2").start(); } } } }
3、经过 Callable 和 Future 建立线程
(1)建立Callable接口的实现类,并实现call()方法,该call()方法将做为线程执行体,而且有返回值。
(2)建立Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
(3)使用FutureTask对象做为Thread对象的target建立并启动新线程。
(4)调用FutureTask对象的get()方法来得到子线程执行结束后的返回值
public class ForWays_Callable implements Callable<Integer>{ @Override public Integer call() throws Exception{ int i = 0; for(;i<100;i++){ System.out.println(Thread.currentThread().getName()+" "+i); } return i; } public static void main(String[] args){ ForWays_Callable ctt = new ForWays_Callable(); FutureTask<Integer> ft = new FutureTask<>(ctt); for(int i = 0;i < 100;i++){ System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i); if(i==20){ new Thread(ft,"有返回值的线程").start(); } } try{ System.out.println("子线程的返回值:"+ft.get()); } catch (InterruptedException e){ e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
call()方法能够有返回值
call()方法能够声明抛出异常
Java5提供了Future接口来表明Callable接口里call()方法的返回值,而且为Future接口提供了一个实现类FutureTask,这个实现类既实现了Future接口,还实现了Runnable接口