有用的(转载) 一个普通的Java类只要从Thread类继承,就可以成为一个线程类。并可通过Thread类的start方法来执行线程代码。虽然Thread类的子类可以直接实例化,但在子类中必须要覆盖Thread类的run方法才能真正运行线程的代码。下面的代码给出了一个使用Thread类建立线程的例子: 001 package mythread; 002 003 public class Thread1 extends Thread 004 { 005 public void run() 006 { 007 System.out.println(this.getName()); 008 } 009 public static void main(String[] args) 010 { 011 System.out.println(Thread.currentThread().getName()); 012 Thread1 thread1 = new Thread1(); 013 Thread1 thread2 = new Thread1 (); 014 thread1.start(); 015 thread2.start(); 016 } 017 } 上面的代码建立了两个线程:thread1和thread2.上述代码中的005至008行是Thread1类的run方法。当在014和015行调用start方法时,系统会自动调用run方法。在007行使用this.getName()输出了当前线程的名字,由于在建立线程时并未指定线程名,因此,所输出的线程名是系统的默认值,也就是Thread-n的形式。在011行输出了主线程的线程名。 上面代码的运行结果如下: main Thread-0 Thread-1
一个普通的Java类只要从Thread类继承,就可以成为一个线程类。并可通过Thread类的start方法来执行线程代码。虽然Thread类的子类可以直接实例化,但在子类中必须要覆盖Thread类的run方法才能真正运行线程的代码。下面的代码给出了一个使用Thread类建立线程的例子:
001 package mythread;
002
003 public class Thread1 extends Thread
004 {
005 public void run()
006 {
007 System.out.println(this.getName());
008 }
009 public static void main(String[] args)
010 {
011 System.out.println(Thread.currentThread().getName());
012 Thread1 thread1 = new Thread1();
013 Thread1 thread2 = new Thread1 ();
014 thread1.start();
015 thread2.start();
016 }
017 }
上面的代码建立了两个线程:thread1和thread2.上述代码中的005至008行是Thread1类的run方法。当在014和015行调用start方法时,系统会自动调用run方法。在007行使用this.getName()输出了当前线程的名字,由于在建立线程时并未指定线程名,因此,所输出的线程名是系统的默认值,也就是Thread-n的形式。在011行输出了主线程的线程名。
上面代码的运行结果如下:
main
Thread-0
Thread-1