实现Runnable接口的run方法
public class RunnableDemo {
public static class RunnableTask implements Runnable {
@Override
public void run() {
System.out.println("thread is running");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableTask());
thread.start();
}
}
继承Thread类并重写run方法
public class ThreadDemo {
private static class MyThread extends Thread {
@Override
public void run() {
System.out.println("thread is running");
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
使用FutureTask方式
public class CallableDemo {
public static class CallerTask implements Callable<String> {
@Override
public String call() throws Exception {
TimeUnit.SECONDS.sleep(3);
return "hello";
}
}
public static void main(String[] args) {
FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
new Thread(futureTask).start();
System.out.println("main...start");
try {
String result = futureTask.get();
System.out.println(result);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("main...end");
}
}
思考
- 调用start方法后线程马上执行吗?
不是的。调用start方法后线程处于就绪状态,就绪状态是指该线程获取了除CPU资源外的其他资源,等待获取CPU资源后才真正处于运行状态。run方法执行完毕,该线程处于终止状态
- 继承Thread有什么优缺点?
优点:使用继承的方式,可以在run方法内部直接通过使用this获取当前线程。
缺点:java不支持多继承
- Runnable与Callable有什么区别?
Runnable实现run方法,无异常抛出,无返回值,Callable实现call方法,可以抛异常,有返回值。