java Thread源码分析

1、Runnable接口源码:

public interface Runnable {
    public abstract void run();
}

2、Thread类与Runnable接口的继承关系

public class Thread implements Runnable{

}

3、构造函数

 public Thread() {
     init(null, null, "Thread-" + nextThreadNum(), 0);
 }
 public Thread(Runnable target) {
     init(null, target, "Thread-" + nextThreadNum(), 0);
 }
 public Thread(ThreadGroup group, Runnable target) {
     init(group, target, "Thread-" + nextThreadNum(), 0);
 }
 public Thread(String name) {
     init(null, null, name, 0);
 }


还有其它的构造方法,此处省略。。。
  这里的第三个参数是设置线程的名称,从下面的代码中可以看出,生成名称的规则是:”Thread-”加上创建的线程的个数(第几个)。

继续查看init方法:

    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
	Thread parent = currentThread();
	SecurityManager security = System.getSecurityManager();
	if (g == null) {
	    /* Determine if it's an applet or not */
	    
	    /* If there is a security manager, ask the security manager
	       what to do. */
	    if (security != null) {
		g = security.getThreadGroup();
	    }

	    /* If the security doesn't have a strong opinion of the matter
	       use the parent thread group. */
	    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);
	    }
	}


        g.addUnstarted();

	this.group = g;
//每个线程都有一个优先级,高优先级线程的执行优先于低优先级线程。每个线程都可以或不可以标记为一个守护程序。当某个线程中运行的代码创建一个新对象时,该新线程的初始优先级被设定为创建线程的优先级,并且当且仅当创建线程是守护线程时,新线程才是守护程序。
	this.daemon = parent.isDaemon();
	this.priority = parent.getPriority();
	this.name = name.toCharArray();
	if (security == null || isCCLOverridden(parent.getClass()))
	    this.contextClassLoader = parent.getContextClassLoader();
	else
	    this.contextClassLoader = parent.contextClassLoader;
	this.inheritedAccessControlContext = AccessController.getContext();
	this.target = target;
	setPriority(priority);
        if (parent.inheritableThreadLocals != null)
	    this.inheritableThreadLocals =
		ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }
初始化时设置了是否为守护线程,优先级,初始化名称。

4、Thread的start方法的实现:

    public synchronized void start() {
        /**
	 * This method is not invoked for the main method thread or "system"
	 * group threads created/set up by the VM. Any new functionality added 
	 * to this method in the future may have to also be added to the VM.
	 *
	 * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
	    stop0(throwableFromStop);
	}
    }
这里主要的是start0方法;查看其实现:

private native void start0();

这里使用了本地调用,通过C代码初始化线程需要的系统资源。可见,线程底层的实现是通过C代码去完成的。

Thread的run方法的实现

    /**
     * If this thread was constructed using a separate 
     * <code>Runnable</code> run object, then that 
     * <code>Runnable</code> object's <code>run</code> method is called; 
     * otherwise, this method does nothing and returns. 
     * <p>
     * Subclasses of <code>Thread</code> should override this method. 
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    public void run() {
	if (target != null) {
	    target.run();
	}
    }
这里的target实际上要保存的是一个Runnable接口的实现的引用:

private Runnable target;
        所以使用继承Thread创建线程类时,需要重写run方法,因为默认的run方法什么也不干。

  而当我们使用Runnable接口实现线程类时,为了启动线程,需要先把该线程类实例初始化一个Thread,实际上就执行了如下构造函数:

 public Thread(Runnable target) {
     init(null, target, "Thread-" + nextThreadNum(), 0);
 }
  即是把线程类的引用保存到target中。这样,当调用Thread的run方法时,target就不为空了,而是继续调用了target的run方法,所以我们需要实现Runnable的run方法。这样通过Thread的run方法就调用到了Runnable实现类中的run方法。

  这也是Runnable接口实现的线程类需要这样启动的原因。


5、sleep(long millis, int nanos) 方法,原来nanos不管用,只能精确到毫秒。

    /**
     * Causes the currently executing thread to sleep (cease execution) 
     * for the specified number of milliseconds plus the specified number 
     * of nanoseconds, subject to the precision and accuracy of system 
     * timers and schedulers. The thread does not lose ownership of any 
     * monitors.
     *
     * @param      millis   the length of time to sleep in milliseconds.
     * @param      nanos    0-999999 additional nanoseconds to sleep.
     * @exception  IllegalArgumentException  if the value of millis is 
     *             negative or the value of nanos is not in the range 
     *             0-999999.
     * @exception  InterruptedException if any thread has interrupted
     *             the current thread.  The <i>interrupted status</i> of the
     *             current thread is cleared when this exception is thrown.
     * @see        Object#notify()
     */
    public static void sleep(long millis, int nanos) 
    throws InterruptedException {
	if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
	}

	if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
				"nanosecond timeout value out of range");
	}

	if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
	    millis++;
	}

	sleep(millis);
    }




转载自: http://www.xuebuyuan.com/460311.html

参考:

http://czj4451.iteye.com/blog/1770003

http://wdhdmx.iteye.com/blog/1202379

http://blog.csdn.net/arkblue/article/details/7742795





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`join()` 方法是 `Thread` 类中的一个方法,它的作用是让调用该方法的线程等待该线程执行完毕。当一个线程使用 `join()` 方法时,调用线程会被阻塞,直到被调用线程执行完毕后才会继续执行。 下面是 `join()` 方法的源码: ``` public final void join() throws InterruptedException { join(0); } ``` 可以看到,`join()` 方法实际上是调用了另一个重载方法 `join(long millis)`,并将参数设置为 0。 ``` public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } } ``` 可以看到,`join(long millis)` 方法是一个同步方法,它首先对传入的参数进行检查,如果小于 0,则会抛出异常。 如果传入的参数为 0,则调用 `wait(0)` 方法,这会使当前线程进入等待状态,直到被调用线程执行完毕后才会被唤醒。 如果传入的参数不为 0,则会在循环中检查被调用线程是否还活着,如果还活着,则调用 `wait(delay)` 方法,这会使当前线程进入等待状态,等待一定的时间后被唤醒。在每次循环中,都会更新当前时间 `now`,并计算需要等待的时间 `delay`。 如果被调用线程已经执行完毕或者等待时间已经超过了传入的参数,则会跳出循环,方法执行完毕。 总的来说,`join()` 方法的本质是利用了 `wait()` 和 `notify()` 方法实现线程的同步和等待。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值