JDK8 之线程Thread小记
一、线程的实现
两种方式:
1.直接继承Thread类
2.实现Runnable接口
上面两种方法都要实现run()方法,最终都会生成一个Thread对像;一般推荐使用第二种办法,因为线程只是实现了Runnable接口,还可以继承其他类。很适合多个相同线程处理同一份资源,能很好的将cpu、代码和数据分开,形成清晰模型,很好的体现了面向对象编程的思想.
//线程初始化private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc) {//必须指定线程名称,具体规则可以看源码if (name == null) {throw new NullPointerException("name cannot be null");}this.name = name;//父线程,即当前的“主线程”Thread parent = currentThread();//获取安全管理器,不是我们本期的重点SecurityManager security = System.getSecurityManager();//线程组为空时,会有一个默认获取线程组的策略//可以说每一个线程都属于一个线程组if (g == null) {//确认它是否为applet应用//如果存在安全管理器,则获取它重写的线程组if (security != null) {g = security.getThreadGroup();}//如果安全性不强,使用父线程组if (g == null) {g = parent.getThreadGroup();}}/* checkAccess regardless of whether or not threadgroup isexplicitly passed in. */g.checkAccess();/** Do we have the required permissions?*/if (security != null) {if (isCCLOverridden(getClass())) {security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);}}//线程组中未启动+1g.addUnstarted();this.group = g;//继承父线程的守护属性this.daemon = parent.isDaemon();//继承父线程的优先级this.priority = parent.getPriority();if (security == null || isCCLOverridden(parent.getClass()))this.contextClassLoader = parent.getContextClassLoader();elsethis.contextClassLoader = parent.contextClassLoader;
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
