实现多线程的两种方法

定义一个类继承Thread类,重写Thread类的run()方法,创建所定义的线程类的实例化对象,调用该对象的start()方法启动线程。线程启动后自动调用run()方法。

public class Test extends Thread {
    static long s,m = 1;
    public static void main(String[] args){
        Test t1 = new Test();
        t1.start();
        for(int i = 1; i < 10000; i++)
            s += i;
        System.out.println("s = " +s);
        System.out.println("m = " +m);
    }
    public void run() {
        for(int j = 1; j<=10; j++)
            m *= j;
    }
}

定义一个类实现Runnable接口,重写Thread类的run()方法,用已经实现了Runnable接口的对象创建一个Thread对象,调用该对象的start()方法启动线程。

public class Test implements Runnable {
    static long s,m = 1;
    public static void main(String[] args){
        Thread t1 = new Thread(new Test());
        t1.start();
        for(int i = 1; i < 10000; i++)
            s += i;
        System.out.println("s = " +s);
        System.out.println("m = " +m);
    }
    public void run() {
        for(int j = 1; j<=10; j++)
            m *= j;
    }
}

这里的Thread类的构造方法:

Thread(Runnable threadOb,String threadName);

threadOb 是一个实现 Runnable 接口的类的实例,并且 threadName 指定新线程的名字。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容