Java多线程(第七章)

来源:互联网 发布:杨辉三角c语言程序六行 编辑:程序博客网 时间:2024/06/05 11:17

1. 线程的状态

  • interrupted静态方法:测试当前线程(current thread)是否是中断状态,执行后将状态标识清除,置为false。
  • isInterrupted实例方法: 测试线程Thread对象(this thread)是否是中断状态,不会清除标识状态。
1. BLOCKED          阻塞Thread state for a thread blocked waiting for a monitor lock. 2. NEW              新建Thread state for a thread which has not yet started. 3. RUNNABLE         运行或就绪Thread state for a runnable thread. 4. TERMINATED       终止Thread state for a terminated thread. 5. TIMED_WAITING    有限等待Thread state for a waiting thread with a specified waiting time. 6. WAITING          无限等待Thread state for a waiting thread. 

这里写图片描述

public class TestThread {    public static void main(String[] args) throws InterruptedException {        MyThread thread1 = new MyThread();        thread1.setName("thread1");        System.out.println("thread1状态为:" + thread1.getState());        thread1.start();        System.out.println("thread1状态为:" + thread1.getState());        Thread.sleep(1000);        System.out.println("thread1状态为:" + thread1.getState());    }}class MyThread extends Thread {    public MyThread() {        System.out.println("进入MyThread构造方法的线程为:" + Thread.currentThread().getName());    }    @Override    public void run() {        System.out.println("当前线程为:" + Thread.currentThread().getName() + "  线程的状态为:"                          + Thread.currentThread().getState());    }}

2. 线程组

可以把线程归到某一个线程组,线程组中可以有线程对象,也可以有线程组,这样的结构类似于树的形式。
执行main方法的线程名为:main,它所属线程组的组名也为:main。
线程或线程组会自动归属到当前线程组中。
当线程组调用interrupt方法时,这个线程组中的线程都会停止。
这里写图片描述

3. SimpleDateFormat非线程安全

解决方案:1) 每次都创建新的实例 2)ThreadLocal

4. 线程中出现的异常

当线程组中的其中一个线程出现异常时,其他线程不会受影响
线程异常处理机制:首先调用自带的异常处理,如果没有,然后调用线程组的异常处理,如果调用默认的。

0 0