Java创建线程的三种方式:
- 继承Thread类重写其run()方法(无返回值)
- 实现Runnable接口实现其run()方法(无返回值)
- 实现Callable接口实现其call()方法,通过FutureTask执行(有返回值)
继承Thread类重写其run()方法
package thread;
/**
* @Author zmp
* @Date 2019/1/17 15:48
* @Description 线程实现方式之继承Thread类,重写run方法,因为run是void所以没有返回值
**/
public class ThreadExample extends Thread{
@Override
public void run() {
System.out.println("继承Thread类线程运行成功,threadName:"+Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadExample threadExample = new ThreadExample();
threadExample.start();
}
}
实现Runnable接口实现其run()方法
package thread;
/**
* @Author zmp
* @Date 2019/1/17 16:07
* @Description 线程实现方式之实现Runnable接口,实现run方法,因为run是void所以没有返回值
**/
public class RunnableExample {
public static void main(String[] args){
Thread runnableThread = new Thread(new RunnableThread());
runnableThread.start();
}
}
class RunnableThread implements Runnable{
public void run() {
System.out.println("实现Runnable类线程运行成功,threadName:"+Thread.currentThread().getName());
}
}
实现Callable接口实现其call()方法,通过FutureTask执行
package thread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* @Author zmp
* @Date 2019/1/17 16:07
* @Description 线程实现方式之实现callable接口,实现call方法,借助FutureTask执行,有返回值
**/
public class CallableExample {
public static void main(String[] args) throws Exception{
Callable<String> callableThread = new CallableThread();
FutureTask<String> futuretask = new FutureTask<String>(callableThread);
new Thread(futuretask).start();
System.out.println("线程返回值:"+futuretask.get());
}
}
class CallableThread implements Callable<String> {
public String call() throws Exception{
System.out.println("实现Callable类线程运行成功,threadName:" + Thread.currentThread().getName());
return "back";
}
}