1、实现多线程有三种方法
继承Thread类
实现Runnable接口
实现Callable接口
1.1、继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
1.2、实现Runnable接口
class RunnableImpl implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
1.3、实现Callable接口
class CallableImpl implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
return "我是Callable线程的返回值";
}
}
1.4、测试
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 线程测试
* @author sunlh
*
*/
public class ThreadTest {
public static void main(String[] args) {
// 通过实现Runnable接口实现多线程
ThreadTest.implRunnable();
// 通过继承Thread类实现多线程
ThreadTest.extThread();
// 通过实现Callable接口来实现多线程
ThreadTest.callableThread();
}
/**
* 通过实现Runnable接口来实现线程
*/
public static void implRunnable() {
Thread thread = new Thread(new RunnableImpl(), "实现Runnable的线程");
thread.start();
}
/**
* 通过继承Thread类来实现线程
*/
public static void extThread() {
MyThread thread = new MyThread();
thread.setName("继承Thread的线程");
thread.start();
}
/**
* 通过实现Future来实现有返回值的线程
*/
public static void callableThread() {
FutureTask<String> task = new FutureTask<>(new CallableImpl());
Thread thread = new Thread(task);
thread.setName("具有返回值的Callable线程");
thread.start();
try {
String result;
result = task.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
2、相关知识:
2.1、Java中线程具有五种状态
初始化
可运行
运行中
阻塞
销毁
这五种状态的转化关系如下: