Java多线程

线程的运行状态

Java多线程_第1张图片

1.线程NEW RUNNING状态:

    @Test
    public void testNewRunnable(){
        Thread t1 = new Thread(() -> {
            logger.debug("running..."); //3.  running... 
        },"t1");

        logger.debug("state:"+t1.getState());  //1.  NEW   新建
        t1.start();
        logger.debug("state:"+t1.getState()); //2.  RUNNING   运行
        logger.debug("state:"+t1.getState());  //4.   TERMINATED  终结

    }

2.线程BLOCKED(阻塞)状态:

    @Test
    public void testBlocked(){
        Thread t2 = new Thread(() -> {
            logger.debug("before...");  // 4.输出before
            synchronized (this){        // 5.抢锁失败
                logger.debug("in...");   // 8.主线程释放锁 t2此时抢到锁 输出in..
            }
        },"t2");

        t2.start(); // 1.t2线程启动
        logger.debug(t2.getState());// 2.t2线程 running状态

        synchronized (this){             //3. 主线程抢到锁    将debug切到t2
            logger.debug(t2.getState());  // 6.此时输出 t2状态为 BLOCKED
        }
                                        // 7. 释放锁 将debug切到t2
        logger.debug(t2.getState());    // 9.此时t2状态为 RUNNABLE
    }

3.线程WAITING(等待)状态:

  // 当线程wait后 释放锁  进入WAITING(等待)状态 直至其他线程唤醒进入RUNNABLE(就绪)状态
    @Test
    public void testWaiting(){
        Thread t3 = new Thread(() -> {
            logger.debug("before..");   // 3. before..
            synchronized (this){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"t3");

        logger.debug(t3.getState());  //1. NEW
        t3.start();
        synchronized (this){          // 2. debug切换到t3
            logger.debug(t3.getState()); // 4. WAITING
            this.notify();               // 5.唤醒线程
            logger.debug(t3.getState());  // 6. BLOCKED
        }
        logger.debug(t3.getState());   //7. RUNNABLE 就绪
    }

你可能感兴趣的:(java,开发语言)