1. 查看线程是否还存活

  1. package tet;public class kk extends Thread{
  2. //1. 查看线程是否还存活
  3. public void run(){
  4. for(int i=0;i<5;i++)
  5. PrintName(2);
  6. }
  7.  
  8. public void PrintName(int i){
  9. System.out.println(i+": "+Thread.currentThread().getName());
  10. }
  11.  
  12. public static void main(String[] args) {
  13. //把main建立出来当做子线程
  14. kk mythread = new kk();
  15. mythread.setName("Thread");
  16.  
  17. System.out.println("before:"+mythread.isAlive());
  18. mythread.start();
  19. System.out.println("after:"+mythread.isAlive());
  20.  
  21. for(int i=0;i<5;i++)
  22. mythread.PrintName(1);
  23.  
  24. System.out.println("after:"+mythread.isAlive());
  25. }
  26. }

结果:

  1. before:false
  2. after:true
  3. 1: main
  4. 1: main
  5. 1: main
  6. 2: Thread
  7. 2: Thread
  8. 2: Thread
  9. 2: Thread
  10. 2: Thread
  11. 1: main
  12. 1: main
  13. after:false

2. 状态监测

notify是唤醒wait的,wait可以是自己运行,也可以是别的程序运行;

结果:

  1. class MyThread extends Thread{
  2.  
  3. boolean tmp_wait = false; //是否等待
  4.  
  5. MyThread(){
  6. System.out.println(getName()+" : construct");
  7. }
  8. public void run(){
  9. System.out.println(getName()+" : running");
  10. startWait();
  11. try {
  12. Thread.sleep(1000);
  13. } catch (InterruptedException e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. }
  17. }
  18.  
  19. //注意:必须要同步
  20. synchronized void startWait() {
  21. try {
  22. while(!tmp_wait) {
  23. System.out.println(getName()+" : waiting");
  24. wait();
  25. }
  26. }
  27. catch(InterruptedException exc) {
  28. System.out.println(getName()+"interrupted");
  29. }
  30. }
  31. //注意:一定要同步,不同步不会编译报错,运行会出错,可以试试
  32. synchronized void notice() {
  33. tmp_wait = true;
  34. notify();
  35. }
  36.  
  37. }
  38.  
  39. public class kk {
  40. public static void main(String args[]) {
  41. System.out.println("hello world");
  42. MyThread t = new MyThread();
  43. try{
  44. t.setName("thread1");
  45. showThreadStatus(1, t);
  46. t.start();
  47. Thread.sleep(50);
  48. showThreadStatus(2, t);
  49.  
  50. t.notice(); //唤醒wait
  51. Thread.sleep(50);
  52. showThreadStatus(3, t);
  53.  
  54. if(t.isAlive()){
  55. showThreadStatus(4, t);
  56. }
  57. while(t.isAlive()){}
  58.  
  59. showThreadStatus(5, t);
  60.  
  61. }catch(InterruptedException e){
  62. e.printStackTrace();
  63. }
  64.  
  65. }
  66.  
  67. static void showThreadStatus(int num, Thread t){
  68. System.out.println("num="+num+" ;name="+t.getName()+" ; status="+t.getState()+" ; live="+t.isAlive());
  69. }
  70.  
  71. }

结果:

  1. hello world
  2. Thread-0 : construct
  3. num=1 ;name=thread1 ; status=NEW ; live=false
  4. thread1 : running
  5. thread1 : waiting
  6. num=2 ;name=thread1 ; status=WAITING ; live=true
  7. num=3 ;name=thread1 ; status=TIMED_WAITING ; live=true
  8. num=4 ;name=thread1 ; status=TIMED_WAITING ; live=true
  9. num=5 ;name=thread1 ; status=TERMINATED ; live=false

3. 中断线程

  1. package tet;
  2.  
  3. public class kk implements Runnable {
  4. public void run() {
  5. try {
  6. System.out.println("in run() - 将运行 work2() 方法");
  7. work2();
  8. System.out.println("in run() - 从 work2() 方法回来");
  9. }
  10. catch (InterruptedException x) {
  11. System.out.println("in run() - 中断 work2() 方法");
  12. return;
  13. }
  14. System.out.println("in run() - 休眠后执行");
  15. System.out.println("in run() - 正常离开");
  16. }
  17. public void work2() throws InterruptedException {
  18. while (true) {
  19. if (Thread.currentThread().isInterrupted()) {
  20. System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
  21. Thread.sleep(2000);
  22. System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
  23. }
  24. }
  25. }
  26. public void work() throws InterruptedException {
  27. while (true) {
  28. for (int i = 0; i < 100000; i++) {
  29. int j = i * 2;
  30. }
  31. System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted());
  32. if (Thread.interrupted()) {
  33. System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
  34. throw new InterruptedException();
  35. }
  36. }
  37. }
  38. public static void main(String[] args) {
  39. kk si = new kk();
  40. Thread t = new Thread(si);
  41. t.start();
  42. try {
  43. Thread.sleep(2000);
  44. }
  45. catch (InterruptedException x) {
  46. }
  47. System.out.println("in main() - 中断其他线程");
  48. t.interrupt();
  49. System.out.println("in main() - 离开");
  50. }
  51. }

结果:

  1. in run() - 将运行 work2() 方法
  2. in main() - 中断其他线程
  3. in main() - 离开
  4. C isInterrupted()=true
  5. in run() - 中断 work2() 方法

JAVA练手--线程(Thread)的更多相关文章

  1. 20个Java练手项目,献给嗜学如狂的人

    给大家推荐一条由浅入深的JAVA学习路径,首先完成 Java基础.JDK.JDBC.正则表达式等基础实验,然后进阶到 J2SE 和 SSH 框架学习.最后再通过有趣的练手项目进行巩固. JAVA基础 ...

  2. Java中的线程Thread总结

    首先来看一张图,下面这张图很清晰的说明了线程的状态与Thread中的各个方法之间的关系,很经典的! 在Java中创建线程有两种方法:使用Thread类和使用Runnable接口. 要注意的是Threa ...

  3. Java中的线程Thread方法之---interrupt()

    前几篇都介绍了Thread中的几个方法,相信大家都发现一个相似点,那就是sleep,join,wait这样的阻塞方法都必须捕获一个InterruptedException异常,顾名思义就是一个线程中断 ...

  4. Java中的线程Thread方法之---suspend()和resume()

    前篇说到了Thread中的join方法,这一篇我们就来介绍一下suspend()和resume()方法,从字面意义上可以了解到这两个方法是一对的,suspend()方法就是将一个线程挂起(暂停),re ...

  5. 去哪找Java练手项目?

    经常有读者在微信上问我: 在学编程的过程中,看了不少书.视频课程,但是看完.听完之后感觉还是不会编程,想找一些项目来练手,但是不知道去哪儿找? 类似的问题,有不少读者问,估计是大部分人的困惑. 练手项 ...

  6. Java中的线程Thread方法之---join()

    上一篇我们说到了Thread中的stop方法,这一篇我们再来看一下方法join的使用,那么方法Join是干啥用的? 简单回答,同步,如何同步? 怎么实现的? 下面将逐个回答. join方法从字面上的意 ...

  7. Java中的线程Thread方法之---stop()

    搞过Java线程的人都知道,stop这个方法是臭名昭著了,早就被弃用了,但是现在任然有很多钟情与他的人,永远都放不下他,因为从他的字面意思上我们可以知道他貌似可以停止一个线程,这个需求是每个搞线程开发 ...

  8. JAVA练手--集合

    集合框架体系如图所示 Collections:是一个工具类java.util.Collections(可以使用它对集合对象进行操作) Collection:除了map(键值对)其他集合的父类 1. S ...

  9. Java 中的线程 thread

    一.问:线程有哪些状态? new, runnable, running, waiting, dead 线程状态间的流转 二.问:线程实现方式? 实现 Runnable 接口,然后new Thread, ...

随机推荐

  1. Visual Studio Code 基本操作 - Windows 版

    1.Install the .NET SDK 2.Create app: dotnet new console -o myApp cd myApp 3.Run your app:dotnet run

  2. EF一对多的表,模糊查询2个表的数据!

    如用户表和电话表,要求搜索时可以模糊查询姓名和号码.都可以找到包含该字符的所有用户. /// <summary> /// 模糊查询姓名和电话号码,并按姓名排序返回 /// </sum ...

  3. JPA之@GeneratedValue注解

    JPA的@GeneratedValue注解,在JPA中,@GeneratedValue注解存在的意义主要就是为一个实体生成一个唯一标识的主键(JPA要求每一个实体Entity,必须有且只有一个主键), ...

  4. iOS 获取 UITabViewController 和 UINavigationController 的图标位置

    这些图标是放在 UITabBar 和 UINavigationBar 里的.所以只要遍历它们的 subViews,找到类型是 UIButton 的就可以了. 所有想获取它们的相对位置很容易. 获取到相 ...

  5. HTML防止input回车提交表单

    原链接:https://blog.csdn.net/ligang2585116/article/details/44699567 自动提交情况说明: 1.默认情况下,单个输入框,无论按钮的type=& ...

  6. “全栈2019”Java第一百一十三章:什么是回调?回调应用场景详解

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

  7. Java io流完成复制粘贴功能

    JAVA 中io字节输入输出流 完成复制粘贴功能: public static void main(String[] args) throws Exception{        // 创建输入流要读 ...

  8. 在eclipse中,用maven创建web项目

    备注:该文档是之前学习时,根据网上其他童鞋的经验自己测试后梳理,如有侵权,请勿怪,感谢! 1.在eclipse中用maven创建项目,右键new>>Maven Project 2.点击ne ...

  9. leetcode-383-Ransom Note(以空间换时间)

    题目描述: Given an arbitrary ransom note string and another string containing letters from all the magaz ...

  10. appium获取toast方法

    配置toast请注意: 1.指定desired_caps["automationName"] = "UiAutomator2" 2.要求安装jdk1.8 64位 ...