通过New Thread的方式
LiftOff.java
package concurrency; public class LiftOff implements Runnable{ protected int countDown = 10; //Default 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!") + ")"; } public void run() { while(countDown-- > 0){ System.out.println(status()); Thread.yield(); } } }
使用了总是分配给main()的那个线程
MainThread.java
package concurrency; public class MainThread { public static void main(String[] args) { LiftOff launch = new LiftOff(); launch.run(); } }
Thread构造器只需要一个Runnable对象,调用Thread对象的start()方法为该线程执行必须的初始化操作.
然后调用 Runnable的run()方法,以便在这个新线程中启动该任务.
BasicThreads.java
package concurrency; public class BasicThreads { public static void main(String[] args) { Thread t = new Thread(new LiftOff()); t.start(); System.out.println("Waiting for LiftOff"); } }