Java多线程的写法有几种,这里列举其中的两种
1. 通过继承Thread 类定义新线程
public class SubclassThread extends Thread {
public void run() {
while (true) {
// 执行线程自身的任务
try {
sleep(5 * 1000);
break;
} catch (InterruptedException exc) {
// 睡眠被中断
}
}
}
public static void main(String[] args) {
Thread thread = new SubclassThread();
thread.start();
System.out.println("主程序结束");
}
}
class Counter implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) System.out.println("计数器= " + i);
}
}
public class RunnableThread {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread = new Thread(counter);
thread.start();
System.out.println("主程序结束");
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Counter implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) System.out.println("计数器= " + i);
}
}
public class Runner {
public static void main(String[] args) {
ExecutorService application = Executors.newCachedThreadPool(); //申请一个线程池
application.execute(new Counter()); // 从线程池中运行一个新线程
application.shutdown(); // 关闭线程池
}
}
Runnable:
优点:节约java宝贵的单继承指标。
缺点:运行时需要构建一个Thread实例来运行或者创建线程池服务来运行实现的Runnable。
Thread:
优点:实现的时候代码较为简单。
缺点:实现需要继承Thread。