当前位置: 移动技术网 > IT编程>开发语言>Java > Java线程状态变换过程代码解析

Java线程状态变换过程代码解析

2020年06月23日  | 移动技术网IT编程  | 我要评论

线程状态

  • new:刚创建未启动的线程
  • runnable:正在执行状态
  • blocked:处于阻塞状态的线程
  • waiting:正在等待另一个线程执行特定动作的线程
  • timed_waiting:等待另一个线程执行时间到达指定时间
  • terminated:线程退出执行
public class teststate {
  public static void main(string[] args) {
    thread thread = new thread(()->{
      for (int i = 0; i < 5; i++) {
        try {
          thread.sleep(1000);
        } catch (interruptedexception e) {
          e.printstacktrace();
        }
      }
      system.out.println("/////");
    });

    //观察线程状态
    thread.state state = thread.getstate();
    system.out.println(state); //new状态

    thread.start();
    state = thread.getstate();
    system.out.println(state);//run状态

    while (state!=thread.state.terminated){
      try {
        thread.sleep(100);
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
      state = thread.getstate();//更新线程状态
      system.out.println(state);//输出状态
    }
  }
}

线程礼让

  • 当前正在执行的线程暂停,但是不会阻塞
  • 当前线程失去处理机,编程就绪状态
  • 礼让是否成功取决于cpu,如果礼让成功,则等待下一次调度
public class testyield {
  public static void main(string[] args) {
    myyield myyield = new myyield();

    new thread(myyield,"a").start();
    new thread(myyield,"b").start();
  }
}

class myyield implements runnable{
  @override
  public void run() {
    system.out.println(thread.currentthread().getname()+"线程开始执行");
    thread.yield();
    system.out.println(thread.currentthread().getname()+"线程停止执行");
  }
}

执行结果:

线程强制执行到结束

  • 使用join()方法
  • 使用join()方法的线程会强制执行直到结束,不会让出处理机
public class testjoin implements runnable{
  @override
  public void run() {
    for (int i = 0; i < 1000; i++) {
      system.out.println("强制执行线程来了"+i);
    }
  }

  public static void main(string[] args) throws exception{
    testjoin testjoin = new testjoin();
    thread thread = new thread(testjoin);
    thread.start();

    for (int i = 0; i < 500; i++) {
      if(i==200){
        thread.join();
      }
      system.out.println("主线程"+i);
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网