一、线程的实现
两种方式:
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 is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
//线程组中未启动+1
g.addUnstarted();
this.group = g;
//继承父线程的守护属性
this.daemon = parent.isDaemon();
//继承父线程的优先级
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;