Thread类

一 重要方法

start()

join()

interrupt()

isInterrupted()

static interrupted()

static yeild()

static sleep()

static currentThread()

[已经废弃的方法]:

stop():强制停止线程,不安全

suspend():暂停线程,可能导致死锁

resume():恢复线程,可能导致死锁

二 重要属性

1)id: 唯一且终生不变. 线程终止之后可以再被使用

2)name: 线程名称

3)state: 线程状态

4)daemon: 标识线程是否为守护线程

5)priority: 优先级

6)threadGroup: 线程组

7)interruption: 中断标识

三 线程状态

NEW: 新建状态,即创建Thread对象之后,调用start()方法之前线程所处的状态

BLOCKED: 阻塞状态,当线程试图进入synchronized区域,等待同步锁时的状态

TIMED_WAITING: 时间等待状态,线程调用sleep()方法之后进入该状态

WAITING: 等待状态,线程调用了Object.wait()方法之后进入该状态

TERMINATED: 终止状态,线程的run()方法运行结束之后的状态

RUNNABLE: 可运行状态,或者正在运行的状态

线程运行状态:

import java.util.concurrent.CountDownLatch;
public class ThreadStateDemo {
	public static CountDownLatch latch = new CountDownLatch(1);
	public static void main(String[] args) throws Exception {
		Thread t1 = new Thread(new Runnable() {
			private String name = "T1";
			@Override
			public void run() {
				try {
					System.out.println(name + " before sleep()");
					Thread.sleep(30000);
					System.out.println(name + " after sleep()");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		Thread t2 = new Thread(new Runnable(){
			private String name = "T2";
			@Override
			public void run() {
				System.out.println(name + " before syncMethod()");
				syncMethod();
				System.out.println(name + " after syncMethod()");
			}
		});
		Thread t3 = new Thread(new Runnable(){
			private String name = "T3";
			@Override
			public void run() {
				System.out.println(name + " before syncMethod()");
				syncMethod();
				System.out.println(name + " after syncMethod()");
			}
		});
		Thread.State state1 = t1.getState();
		System.out.println("线程状态: " + state1); //NEW
		t1.start();
		t2.start();
		Thread.sleep(2000);
		t3.start();
		Thread.sleep(2000);
		Thread.State state2 = t1.getState();
		System.out.println("线程状态: " + state2); //TIMED_WAITING
		Thread.State state3 = t2.getState();
		System.out.println("线程状态: " + state3); //WAITING
		Thread.State state4 = t3.getState(); //BROKEN
		System.out.println("线程状态: " +state4);
		ThreadStateDemo.latch.countDown(); //唤醒Run
		Thread.sleep(5000);
		Thread.State state5 = t2.getState();
		System.out.println("线程状态: " + state5); //TERMINATED
		Thread.State state6 = Thread.currentThread().getState();
		System.out.println("线程状态: " + state6); //RUNNABLE
	}
	public synchronized static void syncMethod() {
		try {
			ThreadStateDemo.latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

四 关于线程中断

interrupt(): 设置线程的中断状态,必须在线程运行(start方法)之后调用才能生效

isInterrrupted(): 获取线程的中断状态

Thread.interrupted(): 清除当前线程的中断状态

说明:

1) 如果某个线程处于TIMED_WAITING或WAITING状态,即已经调用过了sleep()方法或wait()方法,如果再修改线程的中断状态,即调用该线程对象的interrupt()方法,则会从sleep()或wait()方法的位置抛出InterrupedException

2) 如果某个线程的中断状态为true,即已经调用了线程对象的interrupt()方法,当该线程试图进入TIMED_WAITING或WAITING状态,即如果再调用sleep()方法或wait()方法,则会从sleep()或wait()方法的位置抛出InterrupedException

3)为了避免调用sleep()或wait()方法时抛出异常,可以先用isInterrupted()方法检查线程的中断状态,在调用Thread.interruped()方法清除中断状态.

线程中断:

public class ThreadDemo {
	static Object lock = new Object();
	public static void main(String[] args) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				//耗时
				for(int i=0; i<Integer.MAX_VALUE; i++) {
					for(int j=0; j<100; j++) {
						long x = 1;
						long y = 2;
						long z = x * y;
					}
				}
				try {
					System.out.println("线程的中断状态: " + Thread.currentThread().isInterrupted());
					//判断中断状态
					if (Thread.currentThread().isInterrupted()) {
						Thread.interrupted();  //清除中断状态
					}
					//调用sleep()或wait()方法
					synchronized (lock) {
						lock.wait();
					}
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		try {
			t.start();
			t.interrupt();
			System.out.println("isInterrupted: " + t.isInterrupted());
			Thread.sleep(3000);
			System.out.println("isInterrupted: " + t.isInterrupted());
			synchronized(lock) {
				lock.notify();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

五 未捕获异常处理器

setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh): 为线程设置未捕获异常的处理器

static setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh): 为所有线程设置未捕获异常的处理器

接口Thread.UncaughtExceptionHandler仅包含一个方法: public void uncaughtException(Thread t, Throwable e)

代码示例:

import java.lang.Thread.UncaughtExceptionHandler;
class UncaughtExceptionHandlerImpl implements UncaughtExceptionHandler {
	private String name;
	public UncaughtExceptionHandlerImpl(String name) {
		this.name = name;
	}
	@Override
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println(name + " - 捕获到未捕获异常");
		System.out.println(name + " - 抛出异常的线程: " + t);
		System.out.println(name + " - 抛出的异常对象: " + e);
	}
}
public class ThreadDemo {
	static Object lock = new Object();
	public static void main(String[] args) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Object o = null;
				o.toString();//拋出异常
			}
		});
		UncaughtExceptionHandler eHandler = new UncaughtExceptionHandlerImpl("异常处理器");
		UncaughtExceptionHandler defaultHandler = new UncaughtExceptionHandlerImpl("默认的异常处理器");
		t.setUncaughtExceptionHandler(eHandler);
		Thread.setDefaultUncaughtExceptionHandler(defaultHandler);
		t.start();
		//main线程中抛出异常
		Object o = null;
		o.toString();
		System.out.println("main方法将要结束退出");
	}
}

运行结果:

作用说明: 未捕获异常处理器可以在线程异常退出时释放资源,日志记录,防止异常直接展示给客户等

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>