标签:
1、Java创建多线程的方法一:(1)实现Runnable接口并实现其中的run()方法;(2)将Runable对象提交给一个Thread构造器,调用start()方法。
【程序实例】单线程
1 public class LiftOff implements Runnable { 2 3 protected int countDown = 10; 4 5 private static int taskCount = 0; 6 7 private final int id = taskCount++; 8 9 public LiftOff() { 10 } 11 12 public LiftOff(int countDown) { 13 this.countDown = countDown; 14 } 15 16 public String status() { 17 return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + "),"; 18 } 19 20 @Override 21 public void run() { 22 while (countDown-- > 0) { 23 System.out.print(status()); 24 Thread.yield(); 25 } 26 } 27 28 }
1 public class Main { 2 3 public static void main(String[] args){ 4 Thread thread = new Thread(new LiftOff()); 5 thread.start(); 6 System.out.println("Waiting for LiftOff"); 7 } 8 9 }
【运行结果】
【结果分析】
主函数中,主线程(main线程)只创建了一个线程,可以看到输出结果是有序的、可控。此外,可以看出main线程并不会等待创建的线程。
【程序实例2】多线程
1 public class Main { 2 3 public static void main(String[] args) { 4 for (int i = 0; i < 5; i++) 5 new Thread(new LiftOff()).start(); 6 System.out.println("Waiting for LiftOff"); 7 } 8 9 }
【运行结果】
【结果分析】
此时主线程main线程创建并执行了5个线程,各个线程间是独立运行,输出的结果不可控。
标签:
原文地址:http://www.cnblogs.com/acode/p/5786352.html