实现多线程的第三种方法【实现Callable接口】

1、线程类

package com.wyq.thread;

import java.util.concurrent.Callable;

public class Run implements Callable{

	@Override
	public Integer call() throws Exception {
		return  (int) (Math.random()*100);
	}

}

2、测试方法

package com.wyq.thread;

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

public class TestRun {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		Run r = new Run();
		FutureTask ft = new FutureTask<>(r);
		Thread t = new Thread(ft);
		System.out.println("线程是否执行完毕:"+ft.isDone());
		t.start();
		Thread.sleep(100);
		System.out.println("线程是否执行完毕:"+ft.isDone());
		System.out.println("获取结果:"+ft.get());
	}

}

猜你喜欢

转载自blog.csdn.net/wyqwilliam/article/details/94489272
今日推荐