1.基本的线程机制
定义任务
public class LiftOff implements Runnable{ protected int countDown = 10; private static int taskCount = 0; private final int id = taskCount++; public LiftOff(){} public LiftOff(int countDown){ this.countDown = countDown; } public String status() { return "#"+id+"("+(countDown>0?countDown:"Liftoff!")+"). "; } @Override public void run() { while(countDown-->0){ System.out.println(status()); Thread.yield(); } }}
使用Thread类驱动任务
public class BasicThreads { public static void main(String[] args) { Thread t = new Thread(new LiftOff()); t.start(); System.out.println("Waiting for LiftOff"); }}
任务执行完之前垃圾回收器不会回收线程对象。