java线程的实现

版权声明:转载请注明出处 https://blog.csdn.net/doubleguy/article/details/86707762

线程的实现一般有两种方式:

1.通过继承Thread实现

2.通过Runnable接口实现

为啥是两种呢,因为java是单继承机制,如果你要让某个类比如说Cat类实现线程,而这个Cat类已经继承其他类了,那么此时你就不能用继承Thread来实现它的线程了,换用Runnable接口实现。

具体怎么实现呢,看看这个案例,他的功能是让控制台每隔1s输出一个hello world语句,第10s时退出。

代码如下:

1.通过继承Thread实现

package com.test4;

public class LWPTest_exThread {
    public static void main(String [] args){
        Cat cat = new Cat();
        cat.start();
    }
}

class Cat extends Thread{
    int times = 0;

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("hello world!"+times);
            times++;
            if(times == 10)
                break;
        }
    }
}

2.通过Runnable接口实现

package com.test4;

public class LWPTest_exThread {
    public static void main(String [] args){
        Cat cat = new Cat();
        Thread t = new Thread(cat);
        t.start();
    }
}

class Cat implements Runnable{
    int times = 0;

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("hello world!"+times);
            times++;
            if(times == 10)
                break;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/doubleguy/article/details/86707762