工作中用到了Thread,一开始用错了,仔细研究了一下,稍作整理。

前言,今天写代码居然这样写的

new Thread() {

	@Override
public void run() {
System.out.println("test");
} }.run();

天真得以为这样这样会新开启一个线程执行,可是打印了线程的信息之后,发现还是在主线程中。仔细一想,确实我这樣做和调用一个新的Object的toString方法有区别么,根本不会产生神马新的线程。


当然我们的主要实现是在run里面,这也是Thread唯一implements Runnable的一个方法。


于是我们调用start方法,可以在新线程中执行run中的处理逻辑,于是会一位start方法调用了run方法


然后却又不是这样


start的方法代码

/**
* Starts the new Thread of execution. The <code>run()</code> method of
* the receiver will be called by the receiver Thread itself (and not the
* Thread calling <code>start()</code>).
*
* @throws IllegalThreadStateException if the Thread has been started before
*
* @see Thread#run
*/
public synchronized void start() {
if (hasBeenStarted) {
throw new IllegalThreadStateException("Thread already started."); // TODO Externalize?
} hasBeenStarted = true; VMThread.create(this, stackSize);
}

请注意上面的javadoc The code run() method of the receiver will be called by the receiver Thread itself (and not the Thread calling start() )
而究竟是谁这么隐蔽地调用run方法呢
其实是start间接地调用,start调用VMThread的create方法,而系统(OS创建需要的线程),然后JVM调用run方法。直接调用的是jvm。
下面是一篇很geek的文章讲解:

start method

public void start() – this method is responsible for causing the thread (it’s called upon) to begin execution. The name may seem to be a misnomer here as this method only causes and not actually starts the execution. It just schedules the thread and when the CPU Scheduler picks this thread for excution then the JVM calls the run() method to actually start the execution of the thread.

This method will obviously result into two concurrent threads – one, from which this method is called and two, the new thread which executes the run() method of the new Thread instance.

A thread will throw IllegalStateException in case you try to call the start() method on an already started thread instance. That means, a thread can not be started more than once. As per the Java specifications a thread may not be restarted after completing its execution. You’ll be required to create and start the execution of a new thread in that case.

run method

public void run() – this is the only method of the Runnable interface and the classes which intend to execute their code in a separate thread of execution first implement the Runnable interface and subsequently define this method and put all the code expected to be executed in the separate thread inside the scope of this run method.

The other way, such classes can follow for the same is by extending the Thread class and in that case also they should oevrride the run method of the Thread class and put all the code supposed to be executed in the new thread inside the scope of the overriden run method.

Difference between start() and run() methods

start() methods only schedules the thread for execution and not actually begins the execution of the thread. The execution of the thread is started when the JVM calls the run() method of the thread once the CPU Scheduler picks this scheduled thread for execution.

文章来源:http://geekexplains.blogspot.com/2008/05/start-method-vs-run-method-in-java.html

 

 

Thread’s start method and run method的更多相关文章

  1. Invalid character found in method name. HTTP method names must be tokens

      o.apache.coyote.http11.Http11Processor : Error parsing HTTP request header Note: further occurrenc ...

  2. SpringBoot:Invalid character found in method name. HTTP method names must be tokens

    问题背景 关于SpringBoot应用挂了很久之后,会发生Invalid character found in method name. HTTP method names must be token ...

  3. Postman请求后台报错:Invalid character found in method name. HTTP method names must be tokens

    在使用Postman请求后台时Postman出现 开发工具控制台报 信息: Error parsing HTTP request header Note: further occurrences of ...

  4. Modified Least Square Method and Ransan Method to Fit Circle from Data

    In OpenCv, it only provide the function fitEllipse to fit Ellipse, but doesn't provide function to f ...

  5. 关于.ToList(): LINQ to Entities does not recognize the method ‘xxx’ method, and this method cannot be translated into a store expression.

    LINQ to Entities works by translating LINQ queries to SQL queries, then executing the resulting quer ...

  6. java代码中init method和destroy method的三种使用方式

    在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...

  7. Day04 -玩弄Ruby的方法:instance method与class method

    前情提要在第三天时,我们解说了如何在class里用include与extend,去使用module的method. Include is for adding methods to an instan ...

  8. tomcat 启动报错 Invalid character found in method name. HTTP method names must be tokens

    解决:Invalid character found in method name. HTTP method names must be tokens   阿里云上弄了一个tomcat,经常半夜发送崩 ...

  9. [Python] Python 之 function, unbound method 和 bound method

    首先看一下以下示例.(Python 2.7) #!/usr/bin/env python # -*- coding: utf-8 -*- class C(object): def foo(self): ...

随机推荐

  1. 学习笔记(一) HTML+CSS基础课程

    这个周把慕课网的<HTML+CSS基础课程>课程学完,内容都是非常非常基础的,不过还是学到了几个小知识点,记下来先. <a>超链接发送邮件 直接上把他的图片给挪过来了,我就不打 ...

  2. attribute和property兼容性分析

    上一篇文章中,详细的分析了他们的区别,请看Javascript中的attribute和property分析 这次,来详细的看下他们的兼容性,这些内容主要来自于对于jQuery(1.9.x)源代码的分析 ...

  3. CircleImageView 圆形图片头像实现

    package com.view.drop; import android.content.Context; import android.content.res.TypedArray; import ...

  4. [原]容器学习(一):动手模拟spring的IoC

    介绍 学习经典框架的实现原理以及设计模式在其实际中的运用,是非常有必要的,可以让我们更好进行面向对象. 本篇文章就来模拟Spring的IOC功能,明白原理后,可以更好的使用它,进而为进行面向对象提供一 ...

  5. iOS中Blocks的介绍

    1. 什么是Blocks Blocks是C语言的扩充功能.如果用一句话来概括就是:带有自动变量的匿名函数. 第一次看见Blocks的时候,感觉很类似C语言的函数指针,尤其是Block类型变量,更是有极 ...

  6. oracle重新启动步骤

    1. 停应用层的各种程序. $lsnrctl stop   3. 在独占的系统用户下,备份控制文件: SQL>alter database backup controlfile to trace ...

  7. twisted的一些代码

    之前用swoole(1.7.19)写的一段程序在数据量大的时候存在内存泄漏,改为twisted(15.4)实现,自测无误,记录如下(两者cpu占用率90%时吞吐rps能从120提升到1000). #! ...

  8. MySQL 5.6.19 二进制安装

    1.        操作系统 CentOS release 6.2 (Final) 2.        创建用户和组 [root@mymaster1 ~]# groupadd mysql [root@ ...

  9. JS 严格模式

    标志 "use strict"; //老版本浏览器会自动忽略 调用 //整个文件调用 (function(){ "use strict"; })(); //单个 ...

  10. Android开源资料大集合_架构&UI

    1. Anroid开源框架架 https://github.com/kymjs/KJFrameForAndroidhttp://www.oschina.net/p/thinkandroid http: ...