java多线程

来源:互联网 发布:网络宣传方式 编辑:程序博客网 时间:2024/06/04 23:29

在java中实现多线程,有两种方法,一种是继承Thread类,另一种是实现Runable接口。

对于继承Thread类,代码框架如下:

class 类名 extends Thread{方法1;方法2;…public void run(){// other code…}属性1;属性2;… }

举个简单的例子:

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.start();        h2.start();    }     private String name;}

然后运行结果可能如下:

A运行     0

B运行     0

B运行     1

B运行     2

B运行     3

B运行     4

A运行     1

A运行     2

A运行     3

A运行     4

因为需要用的CPU的资源,所以每次运行的结果基本上不会一样的。

注意一点:虽然我们在class里实现的方法是run(),但在main中我们调用的是start(),,不过在实际程序调用的还是run()。

那么:为什么不能直接调用run()呢?

先看一下start源代码:

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异常。


通过Runnable接口实现:

大致框架:

class 类名 implements Runnable{方法1;方法2;…public void run(){// other code…}属性1;属性2;… }

小例子:

class hello implements Runnable {     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");        Thread demo= new Thread(h1);        hello h2=new hello("线程B");        Thread demo1=new Thread(h2);        demo.start();        demo1.start();    }     private String name;}

可能的结果:

线程A运行     0

线程B运行     0

线程B运行     1

线程B运行     2

线程B运行     3

线程B运行     4

线程A运行     1

线程A运行     2

线程A运行     3

线程A运行     4


原创粉丝点击