本博客系列是学习并发编程过程中的记录总结。由于文章比较多,写的时间也比较散,所以我整理了个目录贴(传送门),方便查阅。
thread
类是java中实现多线程编程的基础类。本篇博客就来介绍下thread
类的常用api和常见用法。
thread
类常用的方法如下:
还有thread
类提供了功能丰富的构造函数,大家可以选合适的使用
public class mythread { public static void main(string[] args) { thread thread = thread.currentthread(); //这个方法返回的是当前线程所在线程组以及这个线程组的子线程组内活动的线程数 //这个值是一个估计值,所以这个方法的应用场景不大 int activecount = thread.activecount(); system.out.println("当前系统中活动线程数["+activecount+"]"); //向标准错误输出流输出当前的线程栈,不会阻断程序的继续执行 thread.dumpstack(); //获取所有线程栈信息 map<thread, stacktraceelement[]> allstacktraces = thread.getallstacktraces(); //获取类加载器 classloader contextclassloader = thread.getcontextclassloader(); //获取当前线程名字 string threadname = thread.getname(); system.out.println("current thread name["+threadname+"]"); //获取当前线程id long threadid = thread.getid(); system.out.println("current thread id["+threadid+"]"); //获取当前线程的优先级,一共有1~10总共10个优先级,这个优先级并不是在 //所有平台都生效的 int priority = thread.getpriority(); system.out.println("current thread priority["+priority+"]"); stacktraceelement[] stacktrace = thread.getstacktrace(); system.out.println("-------------stacktrace info--------------"); for (int i = 0; i < stacktrace.length; i++) { stacktraceelement element = stacktrace[i]; system.out.println("classname:["+element.getclassname()+"]"); system.out.println("filename:["+element.getfilename()+"]"); system.out.println("line nunber:["+element.getlinenumber()+"]"); system.out.println("method name:["+element.getmethodname()+"]"); system.out.println("is native method:["+element.isnativemethod()+"]"); system.out.println("------------------------------------------"); } thread.state state = thread.getstate(); system.out.println("thread state:["+state+"]"); threadgroup threadgroup = thread.getthreadgroup(); string threadgroupname = threadgroup.getname(); system.out.println("thread group name:["+threadgroupname+"]"); //线程睡眠,调用sleep方法会使得线程进入timed_waiting状态,如果线程已经 //获得了锁资源,调用sleep方法是不会释放这个锁的 thread.sleep(2000,500); thread.sleep(1000); timeunit.seconds.sleep(2); thread thread1 = new thread(new runnable() { @sneakythrows @override public void run() { timeunit.seconds.sleep(100); } }); thread1.start(); thread1.join(50); } }
守护线程可以理解为服务线程,他们的作用就是服务于其他用户线程。当系统中不存在其他用户线程时,这些守护线程也会自动消亡。比如jvm的垃圾清理线程就是守护线程。我们可以使用如下方法查看和设置线程是否是守护线程。
thread.isdaemon(); thread.setdaemon(true);
调用线程的join方法会使得调用线程进入waiting状态,直到被调用的线程执行结束,调用线程才会重新获得执行的机会。
public class mythread { public static void main(string[] args) throws exception { thread thread1 = new thread(new runnable() { @sneakythrows @override public void run() { timeunit.seconds.sleep(100); } }); thread1.start(); thread1.join(); system.out.println("main thread end..."); } }
上面的代码中,main线程调用了thread1的join方法,main线程会被挂起进入waiting状态,直到thread1执行完毕之后,main线程才有机会重新获得执行机会。
join方法还有一个重载方法,这个方法可以指定超时时间。
thread1.join(50);
如果thread1线程在50ms内还没执行完,main线程就可以重新获得执行机会。
调用线程的yield方法不是一定会成功。
先贴上一段对线程中断的总结。
更加易懂的说法(不包括nio部分):
如对本文有疑问, 点击进行留言回复!!
Android 4.0使用Kotlin调用C语言以及汇编语言
Java Class.forName()用法和newInstance()方法原理解析
网友评论