线程状态
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);//输出状态 } } }
线程礼让
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()+"线程停止执行"); } }
执行结果:
线程强制执行到结束
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); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
【java基础】面试常见问题:类和对象,封装继承多态,final关键字,static关键字,类加载过程,双亲委派模型
荐 Java语言基础之JDK1.8新特性(Lambda表达式、函数式接口、Stream流、新的日期API)
网友评论