java线程学习

demo:当启动好几个线程去进行某种长时间的运算时,主线程就有时间完成其他工作。假设主线程结束了其他工作,需要对其子线程的运算结果处理,此时主线程就需要等运算过程结束后才能继续运行。

 

demo的情况使用线程连接thread join.

 

引用:http://www.blogjava.net/jnbzwm/articles/330549.html

 

package com.tang.thread.join;

public class JoinTestDemo {
	
	public static void main(String[] args) throws InterruptedException {
		String threadName = Thread.currentThread().getName();
		
		 System.out.println(threadName + " start.");   
		 
		 CustomThread1 t1 = new CustomThread1();
		 
		 CustomThread t = new CustomThread(t1);
		 
		 t1.start();
		 t.start();
		 t.join();
		 
		 
		 
		 
		 System.out.println(threadName + " end.");   
	}

}

 

 

   

package com.tang.thread.join;

public class CustomThread1 extends Thread{
	
	public CustomThread1(){
	    super("[CustomThread1]Thread");
	}

	@Override
	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName+" start.");
		try {
			for (int i = 0; i < 5; i++) {
				System.out.println(threadName+" loop at "+i);
				Thread.sleep(1000);
			}
			System.out.println(threadName+"end.");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	

}

 

 

   

package com.tang.thread.join;

public class CustomThread extends Thread{
	
	CustomThread1 t1;

	public CustomThread(CustomThread1 t1) {
		super("[CustomThread]Thread");
		this.t1 = t1;
	}

	@Override
	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName+" start.");
		try {
			t1.join();
			System.out.println(threadName+"end.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	

	

}

 

 

结果1:

main start.
main end.
[CustomThread1]Thread start.
[CustomThread1]Thread loop at 0
[CustomThread1]Thread loop at 1
[CustomThread1]Thread loop at 2
[CustomThread1]Thread loop at 3
[CustomThread1]Thread loop at 4
[CustomThread1]Threadend.

 

    

main start.
main end.
[CustomThread1]Thread start.
[CustomThread1]Thread loop at 0
[CustomThread]Thread start.
[CustomThread1]Thread loop at 1
[CustomThread1]Thread loop at 2
[CustomThread1]Thread loop at 3
[CustomThread1]Thread loop at 4
[CustomThread1]Threadend.
[CustomThread]Threadend.

     

main start.
main end.
[CustomThread1]Thread start.
[CustomThread1]Thread loop at 0
[CustomThread]Thread start.
[CustomThread]Threadend.
[CustomThread1]Thread loop at 1
[CustomThread1]Thread loop at 2
[CustomThread1]Thread loop at 3
[CustomThread1]Thread loop at 4
[CustomThread1]Threadend.

 

    

main start.
[CustomThread1]Thread start.
[CustomThread]Thread start.
[CustomThread1]Thread loop at 0
[CustomThread1]Thread loop at 1
[CustomThread1]Thread loop at 2
[CustomThread1]Thread loop at 3
[CustomThread1]Thread loop at 4
[CustomThread1]Threadend.
[CustomThread]Threadend.
main end.

 

你可能感兴趣的:(java线程)