Thread常用方法

来源:互联网 发布:js弹出模态框 编辑:程序博客网 时间:2024/04/30 04:52

本文介绍Thread几个常用方法,如join()、interrupt()。

1、通过interrupt()方法来中断调用线程

public class InterruptTest {public static void main(String[] args) {MyThread thread = new MyThread();thread.start();try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("interrupt-"+thread.getName());thread.interrupt();System.out.println("main end");}}class MyThread extends Thread{@Overridepublic void run() {System.out.println("thread start");double d = 0.0;// 1boolean flag = true;while(flag){System.out.println("running...");for (int i = 0; i < Integer.MAX_VALUE; i++) {d += Math.E+Math.PI;}}//2//try {//while (true) {//System.out.println("running...");//Thread.sleep(500);//}//} catch (InterruptedException e) {//System.out.println(e.getMessage());//}//3//while(!Thread.interrupted()){//System.out.println("running...");//try {//Thread.sleep(20);//} catch (InterruptedException e) {//}//for (int i = 0; i < Integer.MAX_VALUE; i++) {//d += Math.E+Math.PI;//}//}System.out.println("thread end");}}

在main方法中启动线程,然后给其发送中断信号。在线程中用三套代码测试,第一套无法中断线程,第二套通过Thread.sleep报异常来终止,第三套通过检测Thread.interrupted()来终止线程。

2、调用join方法阻塞currentThread线程,知道调用线程结束

public class InterruptTest {public static void main(String[] args) {MyThread thread = new MyThread();thread.start();thread.safeStop();System.out.println("main end");}}class MyThread extends Thread{@Overridepublic void run() {System.out.println("thread start");double d = 0.0;for (int i = 0; i < Integer.MAX_VALUE; i++) {d += Math.E+Math.PI;}System.out.println("thread end");}public void safeStop(){try {System.out.println("before join");join();//阻塞主线程System.out.println("after join");} catch (InterruptedException e) {e.printStackTrace();}}}

在main方法中启动线程,然后调用safeStop()阻塞主线程,直到线程结束。

3、一些常用方法

Thread.sleep(long). 引起线程休眠指定时间

Thread.currentThread.getName(). 获得当前线程及线程名

0 0
原创粉丝点击