提示:自用总结
一、继承Thread类,重写方法
调用start是启动线程,调用.run()则是调用方法输出的线程是main
package com.springboot.tst;
public class TestThread extends Thread {
@Override
public void run() {
System.out.println("当前线程: "+ Thread.currentThread().getName());
}
public static void main(String[] args) {
TestThread testThread = new TestThread();
testThread.start();
}
}
二、实现Runnable接口
runale接口里没有start()方法,但Thread构造函数支持传入Runable
package com.springboot.tst;
public class TestThread implements Runnable{
@Override
public void run() {
System.out.println("当前线程: "+ Thread.currentThread().getName());
}
public static void main(String[] args) {
TestThread testThread = new TestThread();
Thread thread = new Thread(testThread);
thread.start();
}
}
三、实现Callable接口
有返回值,
package com.springboot.tst;
import java.util.concurrent.*;
public class TestThread implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("当前线程:"+ Thread.currentThread().getName());
Thread.sleep(1000);
return "Hello World!";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(new TestThread());
// future.get()是个阻塞方法
System.out.println(Thread.currentThread().getName()+" "+ future.get());
}
}
总结
Thread 其实也是实现了Runable接口