一、java中三种实现线程的方式
- 1.继承线程类:Thread
- 2.实现接口:Runnable
- 3.实现接口:Callable
1.通过继承线程类Thread,然后覆写run()方法来实现线程 。
public class StartByThread {
private static class UseThread extends Thread{
@Override
public void run() {
try {
sleep(1000);//让线程睡眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName()+
":the way start Thread:extends Thread");
}
}
public static void main(String[] args) {
//继承Thread类时,创建线程的两个方式
Thread thread = new Thread(new UseThread());
UseThread usethread = new UseThread();
//启动线程
thread.start();
usethread.start();
}
}
2.通过实现接口Runnable,实现它的run()方法,来实现线程。
问题:为什么在有了继承Thread类来实现线程的时候,还要有实现接口的方式来实现线程?
因为在Java中,类的继承是单继承机制,在继承了Thread类之后,则不能继承其它的类。但是接口是允许多个实现的。
public class StartByRunnable {
private static class UseRunnable implements Runnable{
@Override
public void run() {
try {
Thread.currentThread().setName(
"Thread_UseRunnable");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+":the way start Thread:implements Runnable");
}
}
public static void main(String[] args) {
UseRunnable runnable = new UseRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
3.通过实现接口Callable,实现call()方法,来实现线程。
需要注意的是,Callable接口的实现是具有返回值的,它通过FutureTask类来返回需要的值。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class StartByCallable {
private static class UseCallable implements Callable<String>{
@Override
public String call() throws Exception {
try {
Thread.currentThread().setName("Thread_UseCallable");
Thread.currentThread();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+":the way start Thread:implements Callable");
return "UseCallableResult";
}
}
public static void main(String[] args)
throws InterruptedException, ExecutionException {
UseCallable useCallable = new UseCallable();
FutureTask<String> futureTask =
new FutureTask<String>(useCallable);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("useCallable的返回结果是:"+futureTask.get());
}
}