1. 程式人生 > 其它 >Thread之Callable介面

Thread之Callable介面

技術標籤:# 多執行緒多執行緒threadjava

Callable介面說明

在這裡插入圖片描述

簡單示例

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
 * @author layman
 * @date 2021/2/10
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException,
InterruptedException { Callable<Integer> callable = new Demo01Callable(); FutureTask<Integer> task = new FutureTask(callable); Thread t = new Thread(task); t.setName("測試callable執行緒"); t.start(); System.out.println("執行緒返回的值為: "
+ task.get()); } } class Demo01Callable implements Callable<Integer>{ @Override public Integer call() throws Exception{ System.out.println(Thread.currentThread().getName()+"呼叫了call方法"); int val = (int)(Math.random()*10); System.out.println("準備返回的值是: "
+ val); return val; } }