继承Thread接口
1package com.atguigu.juc.MyLock;
2
3public class ThreadDemo {
4 public static void main(String[] args) {
5 MyThread myThread = new MyThread();
6 myThread.start();
7 }
8
9}
10
11class MyThread extends Thread {
12
13 @Override
14 public void run() {
15 System.out.println("线程" + Thread.currentThread().getName() + "运行了");
16 }
17}
实现Runable接口
1package com.atguigu.juc.MyLock;
2
3public class ThreadDemo {
4 public static void main(String[] args) {
5 Thread thread = new Thread(new MyThread());
6 thread.start();
7
8 }
9
10}
11
12class MyThread implements Runnable {
13
14 @Override
15 public void run() {
16 System.out.println("线程" + Thread.currentThread().getName() + "运行了");
17 }
18}
实现Callable接口
1package com.atguigu.juc.MyLock;
2
3import java.util.concurrent.Callable;
4import java.util.concurrent.ExecutionException;
5import java.util.concurrent.FutureTask;
6
7public class ThreadDemo {
8 public static void main(String[] args) throws ExecutionException, InterruptedException {
9 FutureTask futureTask = new FutureTask(new MyThread());
10 Thread thread = new Thread(futureTask);
11 thread.start();
12 Integer res =(Integer) futureTask.get();
13 System.out.println("res=" + res);
14
15 }
16
17}
18
19class MyThread implements Callable<Integer> {
20
21 @Override
22 public Integer call() throws Exception {
23 System.out.println("线程" + Thread.currentThread().getName() + "运行了");
24 return 1024;
25 }
26}
对比
实现Runable接口的run方法是没有返回值的,而实现Callable接口的call方法有返回值.我们可以根据需要选取不同的方式进行多线程的创建.