zoukankan      html  css  js  c++  java
  • 【转】run方法与start方法的区别

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

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

  • 相关阅读:
    BZOJ 1072: [SCOI2007]排列perm
    BZOJ 1071: [SCOI2007]组队
    HDP集群部署
    使用Kubeadm部署kubernetes集群
    Docker 私有仓库
    Docker Compose
    Dockerfile使用
    Docker应用部署(Mysql、tomcat、Redis、redis)
    Docker 容器的数据卷 以及 数据卷容器
    Docker 服务、镜像、容器简单命令使用
  • 原文地址:https://www.cnblogs.com/XinHuai/p/6830405.html
Copyright © 2011-2022 走看看