JAVA线程join用法

package self;

/*
 *由主线程产生一个副线程,监控副线程的运行时间,如果运行时间过长,则杀掉副线程 
 * 
 */
public class TestThread {
	
	public static void main(String[] args){
	
		//创建副线程
		Thread minorThread = new Thread(new MinorThread());
		//创建主线程,副线程随主线程一起启动
		Thread majorThread = new Thread(new MajorThread(minorThread));
		majorThread.start();
	}

}

class MajorThread implements Runnable {
	
	Thread thread = null;
	
	public MajorThread(Thread thread){
		this.thread = thread;
	}

	@Override
	public void run(){
		
		long startTime = System.currentTimeMillis();
		//启动副线程
		thread.start();
		while(thread.isAlive()){
			try {
				System.out.println("thread is Alive ");
				/*
				 *使用join(1000) 主线程将等待1s,先让thread执行
				 * 如果join() 没有指定等待时间,则默认先让thread执行完毕之后,在执行当前线程
				 */
				thread.join(1000);
				long runningTime = System.currentTimeMillis();
				long endTime = (runningTime-startTime)/1000;
				/*
				 * 如果超过3s thread还没有执行完毕,则直接kill掉thread线程
				 */
				if(endTime>3){
					//中断线程
					thread.interrupt();
					System.out.println("超过3s thread还没有执行完毕,则直接kill掉thread线程");
					//让thread线程执行完
					thread.join();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
		System.out.println("thread is not Alive ... finish!");
	}
}

class MinorThread implements Runnable {

	String[] massages = { "ji hai bo...", 
			"zhang xiao yan...", 
			"hello world...", 
			"OK OK!", 
			"too too" };

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " is start");
		try{
			for (String massage : massages) {
				System.out.println(massage);
				Thread.sleep(1000);
			}
			
		} catch (InterruptedException e) {
			System.out.println("Thread interrupted...................");
			e.printStackTrace();
		} 
	
		/*while (true) {
			//隔一分钟打印一次
			for (String massage : massages) {
				System.out.println(massage);				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
					return;
				}
			}
			if (Thread.interrupted()){
				System.out.println("Thread interrupted");
				try {
					throw new InterruptedException();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		}*/
	}
}

猜你喜欢

转载自568025297.iteye.com/blog/2271958