Java中线程的4种创建方式

1. 继承Thread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ThreadDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread t = new Thread(myThread);
t.start();
System.out.println(Thread.currentThread().getName());
}
}

class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}

2. 实现Runnable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ThreadDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread t = new Thread(myThread);
t.start();
System.out.println(Thread.currentThread().getName());
}
}

class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}

3. 使用CallableFuture创建线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class ThreadDemo {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> future = new FutureTask<>(myThread);
Thread t = new Thread(future);
t.start();
System.out.println(Thread.currentThread().getName());
}
}

class MyCallable implements Callable<Integer> {

@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
return 0;
}
}

4. 使用线程池创建线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ThreadDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建一个具有固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 创建一个任务
Callable<Integer> callable = new MyCallable();
// 提交任务
Future future = executorService.submit(callable);
// 获取任务执行结果 此方法会阻塞
System.out.println(future.get());
// 关闭线程池
executorService.shutdown();
}
}

class MyCallable implements Callable<Integer> {

@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
return 0;
}
}