java多线程--停止一个线程的方法小结(来自java多线程编程核心技术)
来源:互联网 发布:帝国cms 搜索代码 编辑:程序博客网 时间:2024/05/21 09:09
1.中断方法停止线程:
package thread_stop.way;public class MyThread extends Thread {public void run() {try{for (int i = 0; i < 500000; i++) {if (this.interrupted()) {System.out.println("已经是停止状态了,我要求退出");throw new InterruptedException();}System.out.println("i= " + (i + 1));}System.out.println("停止之后的测试");}catch(InterruptedException e){System.out.println("进入Mythread线程状态异常");//e.printStackTrace();}}}
package thread_stop.way;public class SleepThread extends Thread{public void run(){try{System.out.println("run begin...");Thread.sleep(20000);System.out.println("run end...");}catch(InterruptedException e){System.out.println("在sleep中停止一个线程,实际也是抛异常的方法");e.printStackTrace();}}}
package thread_stop.way;public class UseReturnThread extends Thread{public void run(){while(true){//此处可以添加一个boolean 型的标识,如while(flag),然后在catch的异常中将flag=flse即可if(this.interrupted()){System.out.println("停止了...");return;}System.out.println("timer = "+System.currentTimeMillis());}}}
4.测试:
package thread_stop.way;/** * 本实例测试线程停止的方法 * * @author Administrator * */public class Main {public static void main(String[] args) {//excetionStop();//sleepStop();userReturnStopThread();}/** * 在线程抛异常来终止一个线程 */public static void excetionStop() {try {MyThread thread = new MyThread();thread.start();Thread.sleep(2000); // 主线程休眠2秒thread.interrupt(); // 将测试线程置为中断状态} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("主线程终止");}/** * 在休眠中停止线程 */public static void sleepStop(){try{SleepThread thread = new SleepThread();thread.start();Thread.sleep(200);//主线程休眠 ,这里使主线程休眠 ,主要是想测试线程完全启动起来thread.interrupt();}catch(InterruptedException e){System.out.println("主线程异常。。。");e.printStackTrace();}System.out.println("主线程停止。。。");}/** * 使用return +interrupt来停止一个线程 * @throws InterruptedException */public static void userReturnStopThread() {try{UseReturnThread thread = new UseReturnThread();thread.start();Thread.sleep(2000);thread.interrupt();}catch(InterruptedException e){System.out.println("main thread excetion...");e.printStackTrace();}System.out.println("main thread stop");}}
0 0
- java多线程--停止一个线程的方法小结(来自java多线程编程核心技术)
- Java多线程编程核心技术之---停止线程
- java多线程编程核心技术笔记-停止线程interrupt()方法
- Java多线程 线程的停止
- Java多线程编程-停止线程 暂停线程
- Java多线程编程1--基础知识--5种方法停止线程
- java多线程编程核心技术
- 《Java多线程编程核心技术》
- Java 多线程编程核心技术
- [Java多线程编程核心技术]
- 《java多线程编程核心技术》
- java多线程编程核心技术
- Java多线程编程核心技术
- java多线程编程核心技术
- Java多线程编程核心技术
- 《java多线程编程核心技术》读书笔记3:线程间的通信
- java 多线程 停止线程
- JAVA-多线程-停止线程
- word 当前页插入页眉、页脚、页码。要求奇偶页眉不同,而页码连续。
- 01背包模板动态规划
- 117. Populating Next Right Pointers in Each Node II
- VC++ 数据 写入EXCEL文档
- Android案例—装备选择
- java多线程--停止一个线程的方法小结(来自java多线程编程核心技术)
- Spark RDD中的aggregate函数 -JAVA8 lambda风格实现求平均数(不用mean函数)
- leetcode 104. Maximum Depth of Binary Tree
- Lucene初探之索引过程分析(一)
- Struts2 环境搭建
- HashMap、weakHashMap、LinkedHashMap和TreeMap四者区别与联系
- 内核链表
- nginx
- 序列长度 差分约束