记录:java thread Runnable 区别

java中实现多线程的方式有两种:Runnable & Thread

Runnable接口

Runnable接口只有一个run()方法,类要继承Runnable接口,Runnable需要通过Thread启动

public class EchoServer implements Runnable {
    private int SleepTime = 20;
    private String threadName;
    public EchoServer(String threadName) {
        this.threadName = threadName;
    }
    public void run() {
        try {
            for(int i = 0; i < 1000; i++) {
                System.out.println("ThreadName: " + threadName + " --->>>> " + i);
                Thread.sleep(SleepTime);
            }
        } catch(Exception e) {
            exc.printStackTrace();
        } finally {
            try {
                Thread.sleep(200);
            } catch(Exception e1) {
                e1.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        EchoServer echo1 = new EchoServer("echo1");
        EchoServer echo2 = new EchoServer("echo2");
        EchoServer echo3 = new EchoServer("echo3");
        //启动线程
        Thread t1 = new Thread(echo1);
        Thread t2 = new Thread(echo2);
        Thread t3 = new Thread(echo3);

        t1.start();
        t2.start();
        t3.start();
    }
}
Thread

Thread实现了Runnable的接口
类通过继承实现run()的方法

//Thread实现了Runnable接口
public class Thread implements Runnable {
    .......
}

//e.p
public class EchoServer extends Thread {
    public EchoServer() {
        setName("线程名");
    }

    public void run() {
        try {
            for(int i = 0; i < 100; i++) {
                System.out.println("i =====>>>>>>>> " + i)
            }
        } finally {
            Thread.sleep(1000);
        }

    }
    public static void main(String[] args) {
        EchoServer echo = new EchoServer();
        //启动线程
        echo.start();
    }
}

总结

Runnable,Thread 均可以实现java多线程。推荐使用Runnable接口,可以实现多继承。Runnable,Thread最终都要通过Thread.start()来使线程处于运行状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值