【Java多线程】04-state、以及方法

1、AllState

  • 查看线程当前的状态 分为 new->runnable->timed waiting->TERMINATED

/**
 * @author AnQi
 * @date 2020/3/7 10 00:17
 * @description
 */
public class AllState {
    public static void main(String[] args) {

        Thread t = new Thread(()->{
            for(int i = 0 ;i <5;i++){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("......");
            }

        });
        //观察状态
        Thread.State state = t.getState();
        System.out.println(state);  //new

        t.start();
        state = t.getState();
        System.out.println(state);  //runnable

       /* while(state != Thread.State.TERMINATED){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            state = t.getState(); // timed waiting
            System.out.println(state);
        }*/
        while(true){
            int num = Thread.activeCount();
            System.out.println(num);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            state = t.getState(); // timed waiting
            System.out.println(state);
        }

    }
}

2、其他方法

  • isalive 表示线程是否还活着
  • Thread.currentThread() 当前线程
  • setName getName 代理名称
/**
 * 其他方法
 * isalive 表示线程是否还活着
 * Thread.currentThread() 当前线程
 * setName getName 代理名称
 * @author AnQi
 * @date 2020/3/7 10 50:33
 * @description
 */
public class InfoTest {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread().isAlive());
        //设置名称: 真是角色+代理角色
        MyInfo mi= new MyInfo("战斗机");
        Thread t =new Thread(mi);
        t.setName("攻击");
        t.start();
        Thread.sleep(1000);
        System.out.println(t.isAlive());

    }
}
class MyInfo implements  Runnable{
    private String name;
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+name);

    }

    public MyInfo(String name) {
        this.name = name;
    }
}
发布了44 篇原创文章 · 获赞 7 · 访问量 843

猜你喜欢

转载自blog.csdn.net/ange2000561/article/details/104711459