A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© jingyezhige 中级黑马   /  2015-11-14 14:52  /  580 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。
对于直接继承Thread的类来说,代码大致框架是:
1
2
3
4
5
6
7
8
9
10
11
12
class 类名 extends Thread{
方法1;
方法2;

public void run(){
// other code…
}
属性1;
属性2;


}




先看一个简单的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @author Rollen-Holt 继承Thread类,直接调用run方法
* */
class hello extends Thread {

    public hello() {

    }

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

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

    public static void main(String[] args) {
        hello h1=new hello("A");
        hello h2=new hello("B");
        h1.run();
        h2.run();
    }

    private String name;
}




【运行结果】:
A运行     0
A运行     1
A运行     2
A运行     3
A运行     4
B运行     0
B运行     1
B运行     2
B运行     3
B运行     4
我们会发现这些都是顺序执行的,说明我们的调用方法不对,应该调用的是start()方法。
当我们把上面的主函数修改为如下所示的时候:
1
2
3
4
5
6
public static void main(String[] args) {
        hello h1=new hello("A");
        hello h2=new hello("B");
        h1.start();
        h2.start();
    }




然后运行程序,输出的可能的结果如下:
A运行     0
B运行     0
B运行     1
B运行     2
B运行     3
B运行     4
A运行     1
A运行     2
A运行     3
A运行     4
因为需要用到CPU的资源,所以每次的运行结果基本是都不一样的,呵呵。
注意:虽然我们在这里调用的是start()方法,但是实际上调用的还是run()方法的主体。
那么:为什么我们不能直接调用run()方法呢?
我的理解是:线程的运行需要本地操作系统的支持。
如果你查看start的源代码的时候,会发现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public synchronized void start() {
        /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0 || this != me)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
        stop0(throwableFromStop);
    }
}
private native void start0();




注意我用红色加粗的那一条语句,说明此处调用的是start0()。并且这个这个方法用了native关键字,次关键字表示调用本地操作系统的函数。因为多线程的实现需要本地操作系统的支持。
但是start方法重复调用的话,会出现java.lang.IllegalThreadStateException异常。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马