Java线程启动怎么用start()

发布时间:2021-12-13 09:10:53 作者:iii
来源:亿速云 阅读:432

本篇内容介绍了“Java线程启动怎么用start()”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

1、直接调用线程的run()方法

public class TestStart {
    public static void main(String[] args) throws InterruptedException {
       Thread t1 = new Thread(){

           @Override
           public void run() {
               System.out.println("Thread t1 is working..."+System.currentTimeMillis());
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       };
       t1.run();
       Thread.sleep(2000);
       System.out.println("Thread Main is doing other thing..."+System.currentTimeMillis());
    }
}

Java线程启动怎么用start()

可以看到主线程在t1.run()运行之后再过三秒才继续运行,也就是说,直接在主方法中调用线程的run()方法,并不会开启一个线程去执行run()方法体内的内容,而是同步执行。

2、调用线程的start()方法

public class TestStart {
    public static void main(String[] args) throws InterruptedException {
       Thread t1 = new Thread(){

           @Override
           public void run() {
               System.out.println("Thread t1 is working..."+System.currentTimeMillis());
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       };
       t1.start();
       Thread.sleep(2000);
       System.out.println("Thread Main is doing other thing..."+System.currentTimeMillis());
    }
}

Java线程启动怎么用start()

startVSrun1.JPG 可以看到在,在执行完t1.start()这一行之后,主线程立马继续往下执行,休眠2s后输出内容。 也就是说,t1线程和主线程是异步执行的,主线程在线程t1的start()方法执行完成后继续执行后面的内容,无需等待run()方法体的内容执行完成。

“Java线程启动怎么用start()”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 用java调用oracle存储过程总结
  2. 如何解决java转义json出现\u0000 等乱码的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java start

上一篇:Java精确计算BigDecimal类怎么使用

下一篇:JavaScript常用网页特效有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》