记录:java thread Runnable 区别

来源:互联网 发布:最新手游源码 编辑:程序博客网 时间:2024/06/06 19:02

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.ppublic 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()来使线程处于运行状态

0 0
原创粉丝点击