java 多线程

package cn.tyb.thread;

public class ThreadJoin extends Thread{
	private String type;
	private Object o;
	public ThreadJoin(String type){
		this.type=type;
	}
	
	public void run(){
		//测试代码
		int i=0;
		while(true){
			if(i>=10){
				break;
			}
			System.out.println(type+":	"+i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}
			i++;			
		}
		//要放回的值
		o=i;
	}
	
	public Object get(){
		try {
			//若该线程已经执行完了,则返回o
			this.join();
			return o;
		} catch (InterruptedException e) {			
			e.printStackTrace();
			return null;
		}		
	}
	
	public static void main(String[] args) throws InterruptedException{
		ThreadJoin tj1 = new ThreadJoin("A");
		ThreadJoin tj2 = new ThreadJoin("B");
		//这里可以开n个线程
		tj1.start();
		tj2.start();
		
		//线程开完之后再调用获取返回值的方法
		System.out.println(tj1.get());
		System.out.println(tj2.get());
	}
}

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