Thread继承类中的run()方法和start()方法的区别

2 篇文章 0 订阅
2 篇文章 0 订阅

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mythread.www;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class Run {
    public static void main(String[] args){
        MyThread thread=new MyThread();
        thread.setName("myThread");
        thread.run();
        for(int i=0;i<10;i++){
            try {
                int time=(int)(Math.random()*1000);
                Thread.sleep(time);
                System.out.println("main="+Thread.currentThread().getName());
            } catch (InterruptedException ex) {
                Logger.getLogger(Run.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

      这两者大有讲究。

      在高洪岩先生所著《Java多线程编程核心技术》第6页上,对Thread继承类中的start()和run()方法的区别曾经做过解释:

      Thread.java类中的start()方法通知“线程管理器”(原书是线程规划器,鄙人觉得线程管理器这一称谓更贴切些)此线程已经准备就绪,等待调用线程对象的run()方法。这个过程实际上就是让系统安排一个时间来调用Thread中的run()方法,也就是使线程得到运行,启动线程,具有异步的效果。如果调用代码thread.run()就不是异步执行了,而是同步,那么此对象并不交给“线程处理器”来处理,而是由main主线程来调用run()方法,也就是必须等run()方法中的代码执行完之后才可以执行后面的代码。

package com.mythread.www;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class MyThread extends Thread{

    @Override
    public void run(){
        for(int i=0;i<10;i++){
            int time=(int)(Math.random()*1000);
            try {
                Thread.sleep(time);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("run="+Thread.currentThread().getName());
        }
    }
}

 http://blog.csdn.net/xuxurui007/article/details/7685076

上面链接中的文章是一篇相关文章,希望对大家有所帮助。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值