启动线程的三种方式

世界杯瑞典

文章目录

前言一、启动线程的第一种方法:继承Thread类二、启动线程的第二种方式:实现Runnable接口三、启动线程的第三种方式:实现Callable接口

前言

启动线程一共有三种方法:继承类,实现接口,匿名内部类。

一、启动线程的第一种方法:继承Thread类

start()方法的作用是启动一个分支线程,在JVM中开辟一个新的栈空间。 只要新的栈空间,myThread.start()瞬间就结束了,线程就启动成功了。 启动成功的线程会自动调用run方法,并且run方法在分支线的栈底部。

代码如下(示例):

public class Thread01 {

public static void main(String[] args) {

//创建线程对象

MyThread myThread = new MyThread();

//启动线程

myThread.start();

//主线程

for (int i = 0; i <100 ; i++) {

System.out.println("main主线程--->" + i);

}

}

}

class MyThread extends Thread{

@Override

public void run() {

for (int i = 0; i <100 ; i++) {

System.out.println("分支线程---->"+ i);

}

}

}

二、启动线程的第二种方式:实现Runnable接口

代码如下(示例):

public class Thread02 {

public static void main(String[] args) {

//创建线程对象

Thread thread = new Thread(new MyRunnable());

//启动线程

thread.start();

//主线程

for (int i = 0; i <100 ; i++) {

System.out.println("main主线程--->" + i);

}

}

}

class MyRunnable implements Runnable{

@Override

public void run() {

for (int i = 0; i <100 ; i++) {

System.out.println("分支线程---->"+ i);

}

}

}

实现接口启动线程是最常用的方法

也可以使用匿名内部类的方式启动线程

代码如下(示例):

public class Thread03 {

public static void main(String[] args) {

Thread thread = new Thread(new Runnable() {

@Override

public void run() {

for (int i = 0; i <1000 ; i++) {

System.out.println("分支线程-->" + i);

}

}

});

//启动线程

thread.start();

//主线程

for (int i = 0; i <1000 ; i++) {

System.out.println("main主线程--->"+ i);

}

}

}

三、启动线程的第三种方式:实现Callable接口

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.FutureTask;

/***

* 启动线程的第三种方法:实现Callable接口,重写call()方法

*/

public class ThreadTest04 {

public static void main(String[] args) {

//创建一个“未来任务类”对象

FutureTask futureTask = new FutureTask(new Callable() {

@Override

public Object call() throws Exception { //call()方法相当与run()方法,比run方法好,有返回值

System.out.println("call mothed begin!");

Thread.sleep(1000 * 10);

System.out.println("call mothed over!");

int x = 100;

int y = 200;

return x + y;//自动装箱

}

});

//创建线程对象

Thread t = new Thread(futureTask);

//启动线程

t.start();

Object obj = null;

//获得分支线程返回值

try {

//get()方法的执行会导致主线程的阻塞

obj = futureTask.get();

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

System.out.println("获得分支线程的返回值:" + obj );

//如下的代码会等到分支线程执行结束后,才回到主线程中继续执行

System.out.println("Hello CSDN");

}

}