14.1 多线程(1)

来源:互联网 发布:java导入jar包 编辑:程序博客网 时间:2024/05/01 07:13

从线程继承:

--  SimpleThread.javapublic class SimpleThread extends Thread {  private int countDown = 5;  private static int threadCount = 0;  public SimpleThread() {    // Store the thread name:    super(Integer.toString(++threadCount));    start();  }  public String toString() {    return "#" + getName() + "(" + countDown + "), ";  }  public void run() {    while(true) {      System.out.print(this);      if(--countDown == 0)        return;    }  }  public static void main(String[] args) {    for(int i = 0; i < 5; i++)      new SimpleThread();  }} 结果可能是:#1(5), #5(5), #1(4), #4(5), #2(5), #3(5), #2(4), #4(4), #1(3), #5(4), #1(2), #4(3), #2(3), #3(4), #2(2), #4(2), #1(1), #5(3), #4(1), #2(1), #3(3), #5(2), #3(2), #5(1), #3(1), 分析:该线程类里有构造函数,run()方法。每当构造完成时,就自动start()了。在main函数中,总计创建了5个线程,相当于轮转执行每个线程的run()方法。
0 0