java多线程中start和run方法的区别


这篇文章主要介绍了java 线程中start方法与run方法的区别详细介绍的相关资料,在java线程中调用start方法与run方法的区别在哪里? 这两个问题是两个非常流行的初学者级别的多线程面试问题,这里进行详细说明,需要的朋友可以参考下:

线程中start方法与run方法的区别

在线程中,如果start方法依次调用run方法,为什么我们会选择去调用start方法?或者在java线程中调用start方法与run方法的区别在哪里?  这两个问题是两个非常流行的初学者级别的多线程面试问题。当一个Java程序员开始学习线程的时候,他们首先会学着去继承Thread类,重载run方法或者实现Runnable接口,实现run方法,然后调用Thread实例的start方法。但是当他拥有一些经验之后,他通过查看API文档或者其他途径会发现start方法内部会调用run方法,但是我们中的很多人知道面试时被问到的时候才会意识到这个问题的重要性。在这个java教程里,我们将会明白java中开启线程的时候调用start方法和run方法的不同的地方

这篇文章是我们再起在Java多线程上发表的一些文章的后序部分,E.G. Difference between Runnable and Thread in Java AND How to solve Producer Consumer problem in Java using BlockingQueue.如果你还没有读过他们,你可能将会发现他们还是很有趣并且很有用的

在java线程中 start与run的不同

start与run方法的主要区别在于当程序调用start方法一个新线程将会被创建,并且在run方法中的代码将会在新线程上运行,然而在你直接调用run方法的时候,程序并不会创建新线程,run方法内部的代码将在当前线程上运行。大多数情况下调用run方法是一个bug或者变成失误。因为调用者的初衷是调用start方法去开启一个新的线程,这个错误可以被很多静态代码覆盖工具检测出来,比如与fingbugs. 如果你想要运行需要消耗大量时间的任务,你最好使用start方法,否则在你调用run方法的时候,你的主线程将会被卡住。另外一个区别在于,一但一个线程被启动,你不能重复调用该thread对象的start方法,调用已经启动线程的start方法将会报IllegalStateException异常,  而你却可以重复调用run方法

下面是start方法和run方法的demo

线程中的任务是打印线程传入的String值 已经当前线程的名字

这里可以明确的看到两者的区别

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class DiffBewteenStartAndRun {
  
  
   public static void main(String args[]) {
  
  
     System.out.println(Thread.currentThread().getName());
     // creating two threads for start and run method call
     Thread startThread = new Thread( new Task( "start" ));
     Thread runThread = new Thread( new Task( "run" ));
  
  
     startThread.start(); // calling start method of Thread - will execute in
                 // new Thread
     runThread.run(); // calling run method of Thread - will execute in
               // current Thread
  
  
   }
  
  
   /*
    * Simple Runnable implementation
    */
   private static class Task implements Runnable {
     private String caller;
  
  
     public Task(String caller) {
       this .caller = caller;
     }
  
  
     @Override
     public void run() {
       System.out.println( "Caller: " + caller
           + " and code on this Thread is executed by : "
           + Thread.currentThread().getName());
  
  
     }
   }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

猜你喜欢

转载自blog.csdn.net/hp_yangpeng/article/details/79204594