实现一个线程的两种方法【转载】

来源:互联网 发布:mac如何彻底删除软件 编辑:程序博客网 时间:2024/06/06 02:03

实现一个线程的两种方法


一种是声明 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

    for (int i = 0; i < 500; i++) {

      System.out.println(i);

    }

  }

jerry:两种方法效果貌似一样,而且如果一个线程start两次第二次会出现异常。但先前的那个线程正常运行。


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

// public class MyThread  extends Thread {

public class MyThread 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) {

 //   MyThread mt = new MyThread();

 //   mt.start();

    Thread myThread = new Thread(new MyThread());

    myThread.start();

    for (int i = 0; i < 500; i++) {

      System.out.println(i);

    }

  }


 

原创粉丝点击