java线程一般有三种实现方式,分别是继承Thread类、实现Runnable接口和实现Callable<T>接口,三种方式根据其特性,适用的场景也不尽相同。
1、继承Thread类
继承Thread类,实现run方法,不可抛异常,并无返回值
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("当前执行线程:" + currentThread().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread, "t1");
Thread thread2 = new Thread(myThread, "t2");
Thread thread3 = new Thread(myThread, "t3");
Thread thread4 = new Thread(myThread, "t4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
2、实现Runnable()接口
实现Runnable接口,实现run方法,不可抛异常,并无返回值
public class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println("当前执行线程:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread2 myThread = new MyThread2();
Thread thread1 = new Thread(myThread, "t1");
Thread thread2 = new Thread(myThread, "t2");
Thread thread3 = new Thread(myThread, "t3");
Thread thread4 = new Thread(myThread, "t4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
3、实现Callable<T>接口
实现Callable<T>接口,接口中需要覆盖方法public <T> call(),可以抛异常,并有返回值
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
Future<Integer> submit = executor.submit(task);
executor.shutdown();
//第两种实现方法
// Task task1 = new Task();
// FutureTask<Integer> futureTask = new FutureTask<>(task1);
// Thread thread = new Thread(futureTask);
// thread.start();
if (submit.isDone()) {
System.out.println("task任务已完成");
} else {
System.out.println("task任务未完成");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程在执行");
try {
// V get(long timeout, TimeUnit unit):在设置的时间内,获取任务执行结果,若是直到时间截止依旧木有获取到,则会抛一个超时异常
// System.out.println("task执行的结果:" + submit.get(1000, TimeUnit.MILLISECONDS));
System.out.println("task执行的结果:" + submit.get());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
static class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("进入子线程");
Thread.sleep(3000);
int total = 0;
for (int i = 0; i < 10; i++) {
total += i;
}
return total;
}
}
}
Callable一般是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task)