Thread.jone

1.Thread.jone

其他文章的分析。http://www.blogjava.net/vincent/archive/2008/08/23/223912.html

下面来说说我自己的看法:

1. thread.jone是调用thread的wait方法,来实现阻塞当前线程的效果

2.调用wait方法的前提是获得了对象的锁

3.因此thread.jone是synchronized,即需要先获得thread对象的锁。

下面代码,因为holdthread获得了subthread的对象锁,因此主线程当调用jion方法时一直被阻塞,直到 holdthread释放锁。因为holdthread对象执行run的时间明显多于SubThread的时间,因此当holdthread释放锁,主线程发现SubThread已经inactive,直接返回,不发生等待。因此总的执行时间为9000毫秒

public class HoldThread extends Thread {
	Thread t;

	HoldThread(Thread t) {
		 this.t = t;
	}

	@Override
	public void run() {
		synchronized (t) {
			System.out.println("getObjectLock");
			try {
				Thread.sleep(9000);

			} catch (InterruptedException ex) {
				ex.printStackTrace();
			}
			System.out.println("ReleaseObjectLock");
		}

	}

}
public class SubThread extends Thread {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			System.out.println("SubThread Start!");
			sleep(5000);
			System.out.println("SubThread Exit!");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
public class TheaderJoin {
	 
	public static void main(String[] args){
		SubThread thread = new SubThread();
		HoldThread holdThread =new HoldThread(thread);
 
	    
		try {
			System.out.println("t1:" + System.currentTimeMillis());
			
			//holdThread.start();
			//Thread.sleep(1000);
			thread.start();
			System.out.println("t2:" + System.currentTimeMillis());
			thread.join();
			System.out.println("t3:" + System.currentTimeMillis());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.print("Exit Main!");
	}
}
 

 

当前线程阻塞,并且等待thread,有两种情况当前线程可以重新运行起来  

一是其它线程调用,thread.notify()唤醒当前线程

二是thread执行结束,为什么呢?

你可能感兴趣的:(thread)