Java线程启动怎么用start()

本篇内容介绍了“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()”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!