1.实现多线程的方式有多种:
1.1 继承Thread类
1.2 实现Runnable接口
1.3 实现Callable接口
2.代码实现
2.1 继承java.lang.Thread类
public class ThreadDemo {
public static void main(String[] args) {
Thread t1 = new MyThread();
t1.setName("线程1");
t1.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
}
}
2.2 实现java.lang.Runnable接口
public class RunnableDemo {
public static void main(String[] args) {
MyThread02 mt1 = new MyThread02();
Thread t1 = new Thread(mt1);
t1.setName("线程1");
t1.start();
}
}
class MyThread02 implements Runnable{
@Override
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
}
}
2.3 实现java.util.concurrent.Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableDemo {
public static void main(String[] args) throws Exception {
MyThread03 myThread03 = new MyThread03();
FutureTask<Integer> f1 = new FutureTask<Integer>(myThread03);
Thread thread = new Thread(f1);
thread.setName("线程1");
thread.start();
Integer integer = f1.get();
System.out.println(integer);
}
}
class MyThread03 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
for (int i = 1; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
return 1;
}
}
3. 三种实现方式的对比
3.1 继承java.lang.Thread类 : 编写简单,由于Java只能单继承,所以该方式不够灵活
3.2 实现java.lang.Runnable接口 :省去了单继承的弊端,编写代码更加灵活
3.3 实现java.util.concurrent.Callable接口 : 有返回值