Java并发编程-01-线程的创建和线程信息获取

本文介绍了Java中创建线程的两种主要方式:继承Thread类和实现Runnable接口,并阐述了Runnable接口的优势。同时,讲解了线程信息的获取,包括线程ID、名称、优先级和状态,以及线程状态的六个阶段。还提供了线程优先级的测试代码,指出高优先级线程并不总是先结束,线程的Priority属性用于决定CPU使用权限。
摘要由CSDN通过智能技术生成

一、创建线程的方式

1、继承Thread类,覆盖run方法

2、实现Runnable接口,创建Thread类的实例,通过构造方法实现

3、Runnable接口只有一个抽象的run方法,也就是说Runnable接口本身不支持多线程

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

4、Runnable接口多线程的实现

查看Thread类的源代码,可以看到很多构造函数的参数是Runnable类或者Runnable的子类,即通过Thread类的构造方法类启动Runnable接口实现多线程

    /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }


5、Runnable接口的优势

  • 避免单继承的局限,一个类可以继承多个接口。
  • 适合于资源的共享
6、Thread类是Runnable接口的一个实现子类
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值