如何在程序中创建出多条线程?
- 继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("MyThread运行了" + i);
}
}
}
- 实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("MyRunnable运行了" + i);
}
}
}
- 利用Callable接口、FutureTask类来实现
public class MyCallable implements Callable<String> {
@Override
public String call() {
return "base.MyCallable 运行了";
}
}
测试类
public class TestThread {
public static void main(String[] args) throws Exception {
base.MyThread myThread = new base.MyThread();
myThread.start();
Runnable myRunnable = new base.MyRunnable();
new Thread(myRunnable).start();
Callable<String> myCallable = new MyCallable();
FutureTask