一、Thread类中的静态方法

  Thread类中的静态方法是通过Thread.方法名来调用的,那么问题来了,这个Thread指的是哪个Thread,是所在位置对应的那个Thread嘛?通过下面的例子可以知道,Thread类中的静态方法所操作的线程是“正在执行该静态方法的线程”,不一定是其所在位置的线程。为什么Thread类中要有静态方法,这样就能对CPU当前正在运行的线程进行操作。下面来看一下Thread类中的静态方法:

  1、currentThread()

/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
public static native Thread currentThread();

  currentThread()方法返回的是对当前正在执行的线程对象的引用

  举例:

public class Thread01 extends Thread{

    static{
System.out.println("静态代码块的打印:" + Thread.currentThread().getName());
} public Thread01(){
System.out.println("构造函数的打印:" +Thread.currentThread().getName());
} @Override
public void run() {
System.out.println("run方法的打印:" + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args){
Thread01 thread01 = new Thread01();
thread01.start();
}
}

  结果:

静态代码块的打印:main
构造函数的打印:main
run方法的打印:Thread-0

  可以看到,Thread01类中的三个相同的静态方法Thread.currentThread()所操作的不是同一个线程,虽然写在了Thread01内,但是静态代码块和构造函数中的静态方法是随着main线程而被调用的,run方法中的静态方法则是thread01线程调用的。把thread01.start()注释掉

public class Test {
public static void main(String[] args){
Thread01 thread01 = new Thread01();
// thread01.start();
}
}

  结果:

静态代码块的打印:main
构造函数的打印:main

  因为Thread01中的静态代码块和构造方法都是在main线程中被调用的,而run方法是thread01这个线程调用的,所以不一样。

  举例说明上篇说的"this.XXX()"和"Thread.currentThread().XXX()"的区别,this表示的线程是线程实例本身,后一种表示的线程是正在执行"Thread.currentThread.XXX()这块代码的线程"

public class Thread01 extends Thread{

    public Thread01(){
System.out.println("构造函数中通过this调用:" + this.getName());
System.out.println("构造函数中通过静态方法调用:" + Thread.currentThread().getName());
} @Override
public void run() {
System.out.println("run方法中通过this调用:" + this.getName());
System.out.println("run方法中通过静态方法调用:" + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args){
Thread01 thread01 = new Thread01();
thread01.start();
}
}

  结果:

构造函数中通过this调用:Thread-0
构造函数中通过静态方法调用:main
run方法中通过this调用:Thread-0
run方法中通过静态方法调用:Thread-0

  同样的,把thread01.start()这一行注释掉以后

public class Test {
public static void main(String[] args){
Thread01 thread01 = new Thread01();
// thread01.start();
}
}

  结果:

构造函数中通过this调用:Thread-0
构造函数中通过静态方法调用:main

  所以,在Thread01里面通过Thread.currentThread得到的线程对象的引用不一定就是Thread01,要看该方法所在的代码会被哪个线程调用。

  2、sleep(long millis)

/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static native void sleep(long millis) throws InterruptedException;

  sleep(long millis)方法的作用是在指定的毫秒内让当前"正在执行的线程"休眠(暂停执行)。这个"正在执行的线程"是关键,指的是Thread.currentThread()返回的线程。根据JDK API的说法,"该线程不丢失任何监视器的所属权",简单说就是sleep代码上下文如果被加锁了,锁依然在,但是CPU资源会让出给其他线程。

  举例:

public class Thread01 extends Thread{

    @Override
public void run() {
try {
System.out.println("run threadName:" + this.getName());
System.out.println("调用Thread.sleep方法休眠3秒");
Thread.sleep(3000);
System.out.println("run threadName:" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args){
System.out.println("main 开始===" + System.currentTimeMillis());
Thread01 thread01 = new Thread01();
thread01.start();
System.out.println("main 结束=====" + System.currentTimeMillis());
}
}

  结果:

main 开始===1552401515206
main 结束=====1552401515208
run threadName:Thread-0
调用Thread.sleep方法休眠3秒
run threadName:Thread-0

  3、yield()

/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
public static native void yield();

  暂停当前执行的线程,并执行其他的线程。这个暂停是会放弃CPU资源的,并且放弃CPU的时间不确定,有可能刚放弃,就获得CPU资源了,也有可能放弃好一会儿,才会被CPU执行。

  举例说明yield()放弃CPU的时间是不一定的,用户无法指定

public class Thread01 extends Thread{
@Override
public void run() {
for(int i = 1; i <= 500; i++) {
long beginTime = System.currentTimeMillis();
Thread.yield();
long endTime = System.currentTimeMillis();
System.out.println(" 第" + i + "次yield 的时长为:" + (endTime - beginTime) + "ms");
System.out.println("i = " + i);
}
}
}
public class Thread02 extends Thread{
@Override
public void run() {
for(int i = 0; i < 500000; i++) {
List<Integer> list = new ArrayList<>();
list.add(i);
}
}
}
public class Test {
public static void main(String[] args) {
Thread01 thread01 = new Thread01();
thread01.start();
//根据Thread02多开几个线程
Thread02 thread02 = new Thread02();
thread02.start();
Thread02 thread021 = new Thread02();
thread021.start();
Thread02 thread022 = new Thread02();
thread022.start();
Thread02 thread023 = new Thread02();
thread023.start();
Thread02 thread024 = new Thread02();
thread024.start();
}
}

  结果:

.......................................
.......................................
i = 48
第48次yield 的时长为:0ms
i = 49
第49次yield 的时长为:0ms
i = 50
第50次yield 的时长为:1ms
i = 51
第51次yield 的时长为:0ms
i = 52
第52次yield 的时长为:4ms
i = 53
第53次yield 的时长为:0ms
i = 54
第54次yield 的时长为:0ms
.......................................
.......................................
i = 442
第442次yield 的时长为:0ms
i = 443
第443次yield 的时长为:0ms
i = 444
第444次yield 的时长为:1ms
i = 445
第445次yield 的时长为:0ms
i = 446
第446次yield 的时长为:0ms
.......................................
.......................................

  可以看到,yield()方法放弃CPU的时间是不确定的,可能立马就被CPU执行,也可能要等待一会再被CPU执行。

  4、interrupted()

/**
* Tests whether the current thread has been interrupted. The
* <i>interrupted status</i> of the thread is cleared by this method. In
* other words, if this method were to be called twice in succession, the
* second call would return false (unless the current thread were
* interrupted again, after the first call had cleared its interrupted
* status and before the second call had examined it).
*
* <p>A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
*
* @return <code>true</code> if the current thread has been interrupted;
* <code>false</code> otherwise.
* @see #isInterrupted()
* @revised 6.0
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}

  测试当前线程是否处于中断状态,调用该方法,线程中断状态的标识被清除(置为false),也就是说,如果这个方法被连续调用两次,第二次一定会返回false

public class Test {
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().getName() + "线程是否被中断?" + Thread.interrupted());
System.out.println(Thread.currentThread().getName() + "线程是否被中断?" + Thread.interrupted());
}
}

  结果:

main线程是否被中断?true
main线程是否被中断?false

  当然,这也涉及Java的中断机制,留在后面的一篇文章专门讲解。

参考资料:

  Java多线程3:Thread中的静态方法

  Java 并发编程:线程间的协作(wait/notify/sleep/yield/join)

Java多线程4:Thread中的静态方法的更多相关文章

  1. java 多线程 2 Thread中start()和run()的区别

  2. Java多线程3:Thread中的静态方法

    Thread类中的静态方法 Thread类中的静态方法表示操作的线程是"正在执行静态方法所在的代码块的线程".为什么Thread类中要有静态方法,这样就能对CPU当前正在运行的线程 ...

  3. Java多线程01(Thread类、线程创建、线程池)

    Java多线程(Thread类.线程创建.线程池) 第一章 多线程 1.1 多线程介绍 1.1.1 基本概念 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于 ...

  4. JAVA多线程(一) Thread & Runnable

    githut代码地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service/ ...

  5. java多线程创建-Thread,Runnable,callable和threadpool

    java创建多线程的方式有许多种,这里简要做个梳理 1. 继承Thread类 继承java.lang.Thread类,创建本地多线程的类,重载run()方法,调用Thread的方法启动线程.示例代码如 ...

  6. Java 多线程(1)-Thread和Runnable

    一提到Java多线程,首先想到的是Thread继承和Runnable的接口实现 Thread继承 public class MyThread extends Thread { public void ...

  7. Java 多线程 (Thread 类)

    1.多线程 2.卖票 1.多线程实现 两种方式可以实现多线程: 继承 Thread 类,重写 run 方法:定义对象,调用 start 方法 创建类实现 Runnable 接口,作为实参传递给 thr ...

  8. Java 多线程之 Thread 类 和 Runnable 接口初步使用

    目录 Thread 类 Thread之定义线程类 Thread之开启线程 Runnable 接口 Runnable 之定义线程类 Runnable 之开启线程 @ Thread 类 Thread 类是 ...

  9. Java 多线程查找文件中的内容

    学过了操作系统,突然不知道多线程有什么用了. 看了一下百度,发现多线程,可以提升系统利用率 在系统进行IO操作的时候,CPU可以处理一些其他的东西,等IO读取到内存后,CPU再处理之前的操作. 总之可 ...

随机推荐

  1. 005_python对整数的拼接

    一. (1)需要把整数组成的列表或整数字符串混合的列表拼接成字符串,实现如下: arr=[1,2,3,4,"5"] print ','.join(map(str,arr)) pri ...

  2. java 1.5 自动拆箱和装箱的注意事项

    背景 java1.5后引入了自动装箱和自动拆箱的概念 自动拆箱:将引用类型转化为基本数据类型 自动装箱:将基本数据类型装为引用类型 但是实际使用中,什么情况自动拆箱什么情况自动装箱呢? 自动装箱 In ...

  3. KindEditor 开源得富文本编辑器

    正常HTML情况写输入长文本需要textarea 标签 .但textarea 标签局限性很大,切只能输入单一的文本,我们大多情况下看到的新闻类文本信息大多是图文混排得,且有的配有视频和音乐. 我们可以 ...

  4. Kafka Topic Api

    Pom: <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka_2.10 ...

  5. Winform开发框架中的内容及文档管理模块功能介绍

    在开发项目的时候,我们有一些场景需要编辑一些HTML文档,作为内容发布系统的一部分,有时候也需要对一些文档如WORD文档进行编辑管理,这样需要我们对这些内容及文档进行合适的管理.本文主要介绍在WInf ...

  6. 【C#复习总结】探究各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字

    前言 先普及一下线程安全和类型安全 线程安全: 如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码.如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的 ...

  7. 用Flask+Redis维护Cookies池

    Redis数据库:存储微博账号密码 这里需要购买账号 登录后的cookies:键值对的形式保存 GitHub:https://github.com/LXL-YAN/CookiesPool 视频讲解:h ...

  8. Python-爬虫的基本原理

    什么是爬虫 爬虫就是请求网站并提取数据的自动化程序.其中请求,提取,自动化是爬虫的关键!下面我们分析爬虫的基本流程 爬虫的基本流程 发起请求通过HTTP库向目标站点发起请求,也就是发送一个Reques ...

  9. 使用Comparable接口自定义排序

    Employee: package textq; /** * 调用接口Comparable排序 * @author Administrator * */ public class Employee i ...

  10. struts2之配置文件struts.xml详解

    struts配置文件 struts.xml配置参数详解 struts.xml中很大一部分配置默认配置就好了 但是有些还是需要做了解  以便于理解 和修改 <?xml version=" ...