程序的一个重要指标就是在正确性的基础上其运行的速度,那么并发就是提高程序运行速度的重要方法。于是,实现并发的最直接的方式就是在操作系统级别使用“进程”。
一. 线程机制:
1. 定义任务:
在Java中,线程驱动任务可以由Runnable接口来提供。定义任务指的是实现接口Runnable并重写run()方法,一个简单的倒计时例子:
public class LiftOff implements Runnable {
protected int count = 10;
private static int taskcount = 0;
private final int id = taskcount++;
public LiftOff(int count) {
this.count = count;
}
public String status() {
return "#" + id + "(" + (count > 0 ? count : "LiftOff !") + ").";
}
public void run() {
while(count-- > 0) {
System.out.println(status());
Thread.yield();
}
}
}
那么在main()函数中调用它:
public class MainThread {
public static void main(String[] args) {
LiftOff liftOff = new LiftOff();
liftOff.run();
}
}
在控制台的输出则为:#0(9).#0(8).#0(7).#0(6).#0(5).#0(4).#0(3).#0(2).#0(1).#0(Liftoff !)
当从Runnable导出一个类时,那么必须重写run()方法,在run()方法定义自己的任务代码。
2. 当然,我们也可以将任务交给一个Thread构造器,即用Thread来驱动对象LiftOff,代码如下:
public class MainThread {
public static void main(String[] args) {
Thread thread = new Thread(new LiftOff());
thread.start();
}
}
调用Thread的start()方法初始化该线程,并调用线程中run()方法,启动该任务。
还可以添加更多的线程驱动更多的任务,代码如下:
public class MoreThreads{
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
new Thread(new LiftOff()).start();
}
}
}
输出说明不同的任务执行在线程中混在了一起,若machine中有多个处理器,则线程调度器会在这些处理器之间分发线程。