thread和runable的区别

—————–2017.8.17——-
大哥们,下面的文章写错了,不会同步运行的原因是因为调用的是run方法。
http://developer.51cto.com/art/201203/321042.htm


1.runable我实验了一下,同时new了3个LiftOff,他们还是按照顺讯打印出来的,且线程名都是main,线程id也相同。说明直接用run方法是借用主线程来运行程序的,且会排队来运行。代码比较长,但是我没找到csdn有代码折叠功能,知道如何折叠的朋友可以留评论赐教一下哈。

package com.runnablethreads.gc;

public class LiftOff implements Runnable{

    public LiftOff(){
        System.out.println("thread constructor");
    }
    public void run(){
        Thread thread = Thread.currentThread();
        for(int i = 0;i<3;i++){
            System.out.println("new thread"+i);
            System.out.println("Thread Id: " + thread.getId());
            System.out.println("Thread Name: " + thread.getName());
            Thread.yield();
        }
        System.out.println("over");     
    }

}
package com.runnablethreads.gc;

public class MainThread {

    public static void main(String[] args){
        //for(int i = 0; i <5; i++){
            //new Thread(new LiftOff()).start();
        //}
        LiftOff l1=new LiftOff();
        l1.run();
        LiftOff l2=new LiftOff();
        l2.run();
        LiftOff l3=new LiftOff();
        l3.run();
    }
}
结果:
thread constructor
new thread0
Thread Id: 1
Thread Name: main
new thread1
Thread Id: 1
Thread Name: main
new thread2
Thread Id: 1
Thread Name: main
over
thread constructor
new thread0
Thread Id: 1
Thread Name: main
new thread1
Thread Id: 1
Thread Name: main
new thread2
Thread Id: 1
Thread Name: main
over
thread constructor
new thread0
Thread Id: 1
Thread Name: main
new thread1
Thread Id: 1
Thread Name: main
new thread2
Thread Id: 1
Thread Name: main
over

2.thread我也实验了一下(new Thread(new LiftOff()).start();)同时new多个会并行,且线程名不同。

3.Runnable是一个接口,而Thread是一个类。runnable实现了接口还可以继承另一个不同的类,而thread不行。(think in java P666)

4.join方法(例子在thinkinjava P670) —A的run方法里面谢了调用B.join()的方法。则若A执行到B.join()则会挂起等待B的线程执行完毕后加入b的线程继续执行接下来的代码。

5调用A.interrupt会打断try catch里的代码,执行接下来的代码,执行完毕之后,B.join()可以顺利执行

ps:打印线程号小技巧:
Thread thread = Thread.currentThread();System.out.println(“new thread”+i);
System.out.println(“Thread Id: ” + thread.getId());
System.out.println(“Thread Name: ” + thread.getName());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值