run() 方法 VS start() 方法:
public class MultiThread_Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
}
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
实际上 Thread 类也是实现了 Runnable 接口:
class Thread implements Runnable {}
启动 Runnable 实例时,需要放在 Thread 中,然后调用 start() 方法
public class MultiThread_Test {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
new Thread(mr).start();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class MultiThread_Test {
public static void main(String[] args) throws Exception {
ExecutorService es = Executors.newSingleThreadExecutor();
// 自动在一个新的线程上启动 MyCallable,执行 call 方法
Future<Integer> f = es.submit(new MyCallable());
// 当前 main 线程阻塞,直至 future 得到值
System.out.println(f.get());
es.shutdown();
}
}
class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 123;
}
}