java 创建线程的两种方法

来源:互联网 发布:软件开发工具研究 编辑:程序博客网 时间:2024/05/16 10:05






//一种是声明 Thread 的子类,重载 Thread 类的方法 run
public class MyThread  extends Thread {
  public void run() {
    for (int count = 1, row = 1; row < 20; row++, count++) {
      for (int i = 0; i < count; i++)
        System.out.print('*');
      System.out.print('\n');
    }
  }


 //运行时可以有两种方法,A,B.
  public static void main(String[] args) {
    // MyThread mt = new MyThread();//A
    //mt.start();//A
    Thread myThread = new Thread(new MyThread());//B
    myThread.start();//B
    
  }

}




//另一种途径是声明一个类,该类实现 Runnable 接口。然后再实现方法 run。


public class MyThread1 implements Runnable {
  public void run() {
    for (int count = 1, row = 1; row < 20; row++, count++) {
      for (int i = 0; i < count; i++)
        System.out.print('*');
      System.out.print('\n');
    }
  }
//运行时只能有一种方法B.
  public static void main(String[] args) {
   //MyThread1 mt = new MyThread1();
   // mt.start();
    Thread myThread1 = new Thread(new MyThread1());
    myThread1.start();
    for (int i = 0; i < 500; i++) {
      System.out.println(i);
    }
  }
  
}

原创粉丝点击