/**
* Calls the <code>run()</code> method of the Runnable object the receiver
* holds. If no Runnable is set, does nothing.
*
* @see Thread#start
*/
public void run() {
if (target != null) {
target.run();
}
}
当使用继承Thread类方式来生成线程对象时,我们需要重写 run方法,因为Thread类的run
方法此时什么事情也不做。
当使用实现Runnable方式来生成线程对象时,我们需要实现 Runnable接口的 run方法,然
后使用new Thread(new MyThread())(假如MyThread 已经实现了 Runnable接口)来
生成线程对象,这时的线程对象的 run方法就会调用MyThread类的run方法,这样
我们自己编写的 run方法就执行了。 作者: 黄泉 时间: 2014-4-2 22:00
在Java中创建线程有两种方法:继承Thread类和实现Runnable接口。
一、继承Thread类创建线程类(Thread类已经实现了 Runnable接口)
1、Thread类的构造方法有8个,但常用的只有4个,分别为:
Thread类中的两个最主要的方法:
(1)run()—包含线程运行时所执行的代码,即线程需要完成的任务,是线程执行体。
(2)start()—用于启动线程。
2、通过继承Thread类来创建并启动多线程的步骤:
(1)定义Thread类的子类,并覆盖该类的run()方法。
(2)创建Thread子类的实例,即创建线程对象。
(3)用线程对象的start()方法来启动该线程。
例程:
Java 代码
1. public class Thread1 extends Thread{
2. public void run(){
3. System.out.println(this.getName());
4. }
5. public static void main(String args[]){
6. System.out.println(Thread.currentThread().getName());
7. Thread1 thread1 = new Thread1();
8. Thread1 thread2 = new Thread1();
9. thread1.start();
10. thread2.start();
11. }
12. }
public class Thread1 extends Thread{
public void run(){
System.out.println(this.getName());
}
public static void main(String args[]){
System.out.println(Thread.currentThread().getName());
Thread1 thread1 = new Thread1();
Thread1 thread2 = new Thread1();
thread1.start();
thread2.start();
}
}
程序的运行结果如下:
main
Thread-0
Thread-1