java开发实战经典 第9章 多线程
1.继承Thread类
Thread类实在java.lang中定义的,一个类只要继承了Thread类,此类就称为多线程操作类。
在Thread子类中,必须明确地覆写Thread类中的run()方法,此方放为线程的主体。
线程类的定义如下,
class 线程类名称 extends Thread{
属性;
方法;
public void run(){
线程主体;
}
}
代码示例如下,
package java_book;
public class TestThread {
public static void main(String[] args) {
MyThread mt1 = new MyThread("线程A");
MyThread mt2 = new MyThread("线程B");
mt1.start(); // 启动多线程
mt2.start();
}
}
class MyThread extends Thread{
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() { // 覆写Thread类中的run()方法
for (int i=0; i<10; i++) {
System.out.println(name + "运行, i = " + i);
}
}
}
运行结果如下,
线程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
2.为何是调用start()方法
看下Thread类的start()方法代码,如下
实际上此处真正调用的是start0()方法,此方法在声明处使用了native关键字声明,此关键字表示调用本机的操作系统函数,因为多线程的实现需要依靠底层操作系统支持。
同时注意:如果一个类通过继承Thread类来实现,那么只能调用一次start()方法,如果调用多次,将会抛出“IllegalThreadStateException”。
3.实现Runnable接口
通过实现Runnable接口的方式实现多线程,Runnable接口中只定义了一个抽象方法public void run()。
使用Runnable接口实现多线程的格式如下,
class 类名 implements Runnable{
属性;
方法;
public void run(){
线程主体;
}
}
示例代码如下,
package java_book;public class TestRunnable {
public static void main(String[] args) {
MyThreadImplements mt1 = new MyThreadImplements("线程1");
MyThreadImplements mt2 = new MyThreadImplements("线程2");
Thread t1 = new Thread(mt1); // 注意,这里需要使用Thread类进行转化
Thread t2 = new Thread(mt2); // 实际上Thread类是Runnable接口的子类
t1.start();
t2.start();
}
}
class MyThreadImplements implements Runnable{
private String name;
public MyThreadImplements(String name) {
this.name = name;
}
public void run() { // 覆写Runnable接口中的run()方法
for (int i=0; i<10; i++) {
System.out.println(name + "运行, i = " + i);
}
}
}
运行结果如下,
线程1运行, i = 0
线程2运行, i = 0
线程1运行, i = 1
线程2运行, i = 1
线程2运行, i = 2
线程2运行, i = 3
线程2运行, i = 4
线程1运行, i = 2
线程2运行, i = 5
线程1运行, i = 3
线程2运行, i = 6
线程2运行, i = 7
线程1运行, i = 4
线程2运行, i = 8
线程2运行, i = 9
线程1运行, i = 5
线程1运行, i = 6
线程1运行, i = 7
线程1运行, i = 8
线程1运行, i = 9
4.Thread类中的主要方法
本章小结