ITeye博客

用Callable接口实现多线程

pskfire · 2012-11-18 22:04 · Java · 编程语言 · Markdown

package com.threeKindThreads;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class TestCallableThread implements Callable<Integer>{

	
	private int i;
	@Override
	public Integer call() throws Exception {
		// TODO Auto-generated method stub
		for(; i<100; i++) {
			System.out.println(Thread.currentThread() + " " + i);
		}
		return i;
	}

	public static void main(String[] args) {
		
		TestCallableThread thread = new TestCallableThread();
		FutureTask<Integer> task1 = new FutureTask<Integer>(thread);
		FutureTask<Integer> task2 = new FutureTask<Integer>(thread);
		
		for(int i=0; i<100; i++) {
			System.out.println(Thread.currentThread().getName() + " " + i);
			
			if(i == 20) {
				new Thread(task1, "Thread1 with return value").start();
				new Thread(task2, "Thread2 with return value").start();
			}
		}
		
		try {
			System.out.println("return value = " + task1.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。