Thread类

Thread类是在java.lang包中定义的,一个类只要继承了Thread类,此类就称为多线程操作类,Thread子类中,必须明确地覆写Thread类中的run()方法,此方法为线程的主体

【多线程的定义语法】

class  类名称  extends  Thread{

属性...;

方法...;

public void run{  //覆写Thread类中的run()方法,此方法是线程的主体

线程主体;

     }

}

范例:继承Thread类实现多线程

package ThreadDemo01;

class MyThread extends Thread {
	private String name;

	public MyThread(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(name + "运行,i=" + i);
		}
	}
};

public class ThreradDemo01 {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		mt1.run();
		mt2.run();
	}
};

  结果:

线程A运行,i=0
线程A运行,i=1
线程A运行,i=2
线程A运行,i=3
线程A运行,i=4
线程A运行,i=5
线程A运行,i=6
线程A运行,i=7
线程A运行,i=8
线程A运行,i=9
线程B运行,i=0
线程B运行,i=1
线程B运行,i=2
线程B运行,i=3
线程B运行,i=4
线程B运行,i=5
线程B运行,i=6
线程B运行,i=7
线程B运行,i=8
线程B运行,i=9

 

这样并没有启动线程,

如果要正确启动线程,是不能直接调用run()方法的,而应该从Thread类中继承而来的start()方法代码如下:

范例:启动线程

package ThreadDemo01;

class MyThread extends Thread {
	private String name;

	public MyThread(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(name + "运行,i=" + i);
		}
	}
}

public class ThreradDemo01 {
	public static void main(String args[]) {
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		mt1.start();
		mt2.start();
	}
}

  结果:

线程A运行,i=0
线程A运行,i=1
线程A运行,i=2
线程A运行,i=3
线程A运行,i=4
线程A运行,i=5
线程A运行,i=6
线程A运行,i=7
线程A运行,i=8
线程A运行,i=9
线程B运行,i=0
线程B运行,i=1
线程B运行,i=2
线程B运行,i=3
线程B运行,i=4
线程B运行,i=5
线程B运行,i=6
线程B运行,i=7
线程B运行,i=8
线程B运行,i=9

再次运行:

线程A运行,i=0
线程B运行,i=0
线程B运行,i=1
线程B运行,i=2
线程B运行,i=3
线程B运行,i=4
线程B运行,i=5
线程B运行,i=6
线程B运行,i=7
线程B运行,i=8
线程B运行,i=9
线程A运行,i=1
线程A运行,i=2
线程A运行,i=3
线程A运行,i=4
线程A运行,i=5
线程A运行,i=6
线程A运行,i=7
线程A运行,i=8
线程A运行,i=9

从结果上看两个程序是交错运行的,那个线程抢到了CPU那个就可以运行,线程虽然调用的是start()方法,但实际上调用run()方法主体。

如果一个类只能继承Thread类才能事项多线程,则必定会受到单继承局限的影响,所以一般会使用Runnable接口完成

posted on 2011-12-08 18:54  wangbokun  阅读(314)  评论(0编辑  收藏  举报

导航