---
title: "用Callable接口实现多线程"
author: "pskfire"
date: "2012-11-18T22:04:32Z"
tags: []
categories: ["编程语言"]
slug: "callable"
draft: false
lastmod: "2012-11-18T22:04:32Z"
id: 1729157
url: "https://pskfire.iteye.com/blog/1729157"
---

```java
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();
		}
	}
}

```