博客
关于我
Java--多线程(1)Thread
阅读量:338 次
发布时间:2019-03-01

本文共 1012 字,大约阅读时间需要 3 分钟。

多线程的创建一:继承于Thread类

创建多线程的常用方法之一是通过继承Thread类来实现。在Java中,Thread类是实现多线程的基础类,任何继承于Thread类的子类都可以作为一个线程对象。以下是创建这样的线程的具体步骤:

  • 创建一个继承于Thread类的子类
  • 重写Thread类的run()方法,定义线程的执行逻辑
  • 创建Thread类的子类对象
  • 通过此类对象调用start()方法
  • Thread类提供了一些常用的方法来管理线程:

    • start():启动线程,并执行run()方法
    • getName():获取线程的名称
    • setName():设置线程的名称
    • currentThread():返回当前线程(在Thread子类中,为this)
    • yield():让线程让步
    • join():等待线程的完成
    • sleep():线程休眠

    需要注意的是,一个继承于Thread的子类对象只能调用一次start()方法。例如:

    public class TestThread {    public static void main(String[] args) {        MyThread mt = new MyThread();        mt.start();        for (int i = 0; i < 100; i++) {            System.out.println("多线程0");        }    }}class MyThread extends Thread {    @Override    public void run() {        for (int i = 0; i < 100; i++) {            System.out.println("多线程1");        }    }}

    如果需要更灵活地使用run方法,可以考虑使用匿名子类的形式:

    new MyThread() {    @Override    public void run() {        for (int i = 0; i < 100; i++) {            System.out.println("多线程1");        }    }}.start();

    在实际应用中,匿名子类的方式更为常用,因为它可以避免定义一个独立的类,简化代码结构。

    转载地址:http://uoca.baihongyu.com/

    你可能感兴趣的文章
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>