Java Thread and runnable

java中可有两种方式实现多线程,

一种是继承Thread类,(Thread本身实现了Runnable接口,就是说需要写void run 方法,来执行相关操作)

一种是实现Runnable接口

start, 和主线程一起执行,执行的顺序不确定

join,线程们 先执行,当所有的子线程执行完毕后,主线程才执行操作(文章最下面的例子)

 

// 1 Provide a Runnable object, the Thread class itself implements Runnable
//~~~ 1.1
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        output("t1");
    }
});
t1.start();

//~~~ 1.2 is more general
public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("Hello from a thread!");
    }
}
(new Thread(new HelloRunnable())).start();

// 2 Subclass Thread (in simple applications)  The Thread class itself implements Runnable
public class HelloThread extends Thread {
    public void run() {
        System.out.println("Hello from a thread!");
    }
}
 (new HelloThread()).start();

 

 

// thread.join
t1.start()
t2.start()
outputresult // 如果想要等到 两个线程t1, t2 都执行完成,再通过outputresult,在主线程输出结果,需要t1.join(), t2.join()

t1.start()
t2.start()
t1.join()
t2.join()
outputresult

 

posted @ 2015-04-30 13:40  webglcn  阅读(183)  评论(0编辑  收藏  举报