在Thread类中有很多方法值得我们关注一下。下面选取几个进行范例:

1.1、isAlive()方法

  java api 描述如下:

public final boolean isAlive()
Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
Returns:
true if this thread is alive; false otherwise.

  示例代码如下:

package soarhu;

import java.util.concurrent.TimeUnit;

/**
* Created by huaox on 2017/4/17.
*
*/ class ThreadTest extends Thread{ private int count = 5; @Override
public void run() {
System.out.println("3->"+Thread.currentThread().isAlive());
} } public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadTest thread = new ThreadTest();
thread.setName("a");
System.out.println("1->"+thread.isAlive());
thread.start();
TimeUnit.SECONDS.sleep(3);
System.out.println("2->"+thread.isAlive());
}
}

输出结果:

1->false
3->true
2->false

在main线程休眠3秒后,子线程此时已经结束。那么isAlive()方法放回为假。

1.2:sleep()方法

api 文档如下

public static void sleep(long millis)
throws InterruptedException
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. // 线程休眠后不会丢掉它的所属监视器,即如果有锁则不会释放锁。
Parameters:
millis - the length of time to sleep in milliseconds
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
//当休眠的线程被中断时,sleep()方法则会抛出InterruptedException.例如调用该线程的interrupt()方法,那么该异常将被抛出并且线程的中断状态将会被清除,
package soarhu;

/**
* Created by huaox on 2017/4/17.
*
*/ class ThreadTest extends Thread{ private long count = 20; @Override
public synchronized void run() {
count<<=1;
System.out.println("run: "+count);
} synchronized void second(){ //和run方法的锁是同一个锁对象,
try {
count-=5;
Thread.sleep(3000);
System.out.println("second: "+count);
} catch (InterruptedException e) {
e.printStackTrace();
}
} } public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadTest thread = new ThreadTest();
thread.start();
thread.second();//该方法会先于thread的run方法执行
}
}

输出结果:

second: 15
run: 30

由于run和second方法都是同步方法,所以他们的监视器对象是一致的,那么就会进行阻塞访问。当second休眠的时候。run方法没有被执行。说明sleep()方法不会丢掉锁,如果丢掉的话,run()方法会立即得到执行。

package soarhu;

import java.util.concurrent.TimeUnit;

/**
* Created by huaox on 2017/4/17.
*
*/
class ThreadTest extends Thread{
private long count = 20;
@Override
public void run() {
count<<=1;
try {
System.out.println("sleep before: "+Thread.currentThread().isInterrupted());
TimeUnit.SECONDS.sleep(10);//收到interrupt()时,会触发中断异常,并且将中断状态设置为true.
} catch (InterruptedException e) {
System.out.println("catch: "+Thread.currentThread().isInterrupted());//carch块中,中断状态将被清除。设置为false
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadTest thread = new ThreadTest();
thread.start();
Thread.sleep(2000);
thread.interrupt();//给线程发一个中断标志
System.out.println("main: "+thread.isInterrupted());
}
}

输出结果:

sleep before: false
main: false
catch: false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at soarhu.ThreadTest.run(Test.java:17)

Thread.interrupt()并不会真正的中断线程,只是给该线程发送一个中断标志为true的flag

  1. 如果该线程处于阻塞状态,例如在sleep(),wait(),join()阻塞中的线程时,那么该线程将会抛出InterruptedException异常。并且在异常块中将中断标志flag清除掉,即设为false.
  2. 如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个 ClosedByInterruptException
  3. 如果该线程在一个 Selector 中受阻,则该线程的中断状态将被设置,它将立即从选择操作返回,并可能带有一个非零值,就好像调用了选择器的 wakeup 方法一样。
  4. 如果以前的条件都没有保存,则该线程的中断状态将被设置。
  5. 中断一个非活动线程并不会产生任何的副作用。

1.3、 interrupt()方法

public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked,
which may cause a SecurityException to be thrown.如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class,
or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class,
then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel
then the channel will be closed, the thread's interrupt status will be set,
and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set
and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
Throws:
SecurityException - if the current thread cannot modify this thread

1.4、interrupted()方法

public static boolean interrupted()
Tests whether the current thread has been interrupted. The interrupted status 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).//调用两次该方法会返回false
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false. Returns:
true if the current thread has been interrupted; false otherwise.
See Also:
isInterrupted()

1.5、isInterrupted()

public boolean isInterrupted()
Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.//调用该方法不会清除中断状态
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false. Returns:
true if this thread has been interrupted; false otherwise.
See Also:
interrupted()

1.6、如何停止一个线程

package soarhu;

/**
* Created by huaox on 2017/4/17.
*
*/
class ThreadTest extends Thread{
private long count = 0;
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
count++;
}
System.out.println(count);
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadTest thread = new ThreadTest();
thread.start();
Thread.sleep(1000);
thread.interrupt();//给线程发一个中断标志
}
}

输出结果:1000000

可知调用interrupt()方法并不会中断线程,前文api已经很明确的告诉我们了。

public class Test {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread().isInterrupted());
}
}

输出结果:

true
true

上述代码给main线程发送中断信号。然后isInterrupted()方法检测是否发生中断,故两次调用后都显示true.因为该方法并不会清除中断状态。

public class Test {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().interrupt();
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());
}
}

输出结果:

true
false

上述代码给main线程发送中断信号。然后interrupted()方法检测是否发生中断,故第一次调用后显示true.然后设置中断状态为false,所以第二次调用会显示为false.因为该方法会清除中断状态。

那么如何停止一个线程呢?可以使用标记法,return或者异常法来退出线程。

package soarhu;

import java.util.concurrent.TimeUnit;

/**
* Created by huaox on 2017/4/17.
*
*/
class ThreadTest extends Thread{
private long count = 0;
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
if(Thread.currentThread().isInterrupted()){
System.out.println("exit thread current count value is: "+count);
return ;//退出线程
}
count++;
}
System.out.println(count);
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread thread = new ThreadTest();
thread.start();
TimeUnit.MILLISECONDS.sleep(2);
thread.interrupt();
System.out.println("end!");
}
}

输出结果:

end!
exit thread current count value is: 10482

java多线程基本概述(二)——Thread的一些方法的更多相关文章

  1. java多线程基本概述(七)——join()方法

    在很多情况下,主线程创建并启动子线程,如果子线程中有大量的耗时运算,主线程将早于子线程结束,如果想让主线程等待子线程结束后再结束,那么我们可以使用join()方法.调用join()方法的意思是当前线程 ...

  2. “全栈2019”Java多线程第十章:Thread.State线程状态详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  3. Java多线程学习(二)synchronized关键字(2)

    转载请备注地址:https://blog.csdn.net/qq_34337272/article/details/79670775 系列文章传送门: Java多线程学习(一)Java多线程入门 Ja ...

  4. Java多线程学习(二)synchronized关键字(1)

    转载请备注地址: https://blog.csdn.net/qq_34337272/article/details/79655194 Java多线程学习(二)将分为两篇文章介绍synchronize ...

  5. “全栈2019”Java多线程第二十二章:饥饿线程(Starvation)详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  6. “全栈2019”Java多线程第十二章:后台线程setDaemon()方法详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  7. Java多线程中join、yield、sleep方法详解

    在Java多线程编程中,Thread类是其中一个核心和关键的角色.因此,对该类中一些基础常用方法的理解和熟练使用是开发多线程代码的基础.本篇主要总结一下Thread中常用的一些静态方法的含义及代码中的 ...

  8. Java多线程——<一>概述、定义任务

    一.概述 为什么使用线程?从c开始,任何一门高级语言的默认执行顺序是“按照编写的代码的顺序执行”,日常开发过程中写的业务逻辑,但凡不涉及并发的,都是让一个任务顺序执行以确保得到想要的结果.但是,当你的 ...

  9. Java 多线程 - 总结概述

    概述 菜鸟教程: Java 给多线程编程提供了内置的支持. 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务. 多线程是多任务的一种特别的形式,但多线程 ...

随机推荐

  1. 计算机网络之HTTP(上)基础知识点

    计算机网络,应该是我们编程开发.产品上线到正常的运行维护需要考虑的基本条件之一.之前我记录了一篇很简单的计算机的组成(http://www.cnblogs.com/zhangxiongcn/p/636 ...

  2. TableView 多余分割线的处理

    方法一,以下两个方法的实现 - (void)viewDidLoad { [super viewDidLoad]; self.tableView.tableFooterView = [[UIView a ...

  3. Host文件修改后无效的解决办法

    什么是hosts文件? 简单的说,hosts文件是用于本地dns服务(相关主题:什么是DNS缓存,如何清除DNS缓存?)的,采用ip 域名的格式写在一个文本文件当中,Hosts是一个没有扩展名的系统文 ...

  4. [HDU1210] Eddy's 洗牌问题

    Problem Description Eddy是个ACMer,他不仅喜欢做ACM题,而且对于纸牌也有一定的研究,他在无聊时研究发现,如果他有2N张牌,编号为1,2,3..n,n+1,..2n.这也是 ...

  5. ACM 整数划分(四)

    整数划分(四) 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 暑假来了,hrdv 又要留学校在参加ACM集训了,集训的生活非常Happy(ps:你懂得),可是他最近 ...

  6. 1774: [Usaco2009 Dec]Toll 过路费

    1774: [Usaco2009 Dec]Toll 过路费 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 263  Solved: 154[Submit ...

  7. Spring Data JPA 简单查询--接口方法

    一.接口方法整理速查 下表针对于简单查询,即JpaRepository接口(继承了CrudRepository接口.PagingAndSortingRepository接口)中的可访问方法进行整理.( ...

  8. markown编辑器截图粘贴预览,并将图片传至七牛云

    最近在做一个项目,需要实现类似QQ截图后,就是能够在富文本编辑器中粘贴截图并预览. 先看一下效果: 分析一下实现步骤: QQ截图后在编辑器中粘贴,肯定会有一个粘贴事件,即 paste 事件 在事件回调 ...

  9. web从入门开始(6)-----框架

    普通框架 框架概念:就是将一个页面分割成小窗口,每个窗口都是一个网页 框架集和框架页 框架集:<frameset>:主要用来划分窗口的 框架页:<frame>:主要用来指定窗口 ...

  10. 提交任务到Spark

    1.场景 在搭建好Hadoop+Spark环境后,现准备在此环境上提交简单的任务到Spark进行计算并输出结果.搭建过程:http://www.cnblogs.com/zengxiaoliang/p/ ...