关于java:Java-线程

53次阅读

共计 1664 个字符,预计需要花费 5 分钟才能阅读完成。

从工作中返回值

import java.util.ArrayList;
import java.util.concurrent.*;

class TaskWithResult implements Callable<String> { // 要想得到返回值能够实现 Callable 接口, 类型参数是返回值的类型
    private int id;
    public TaskWithResult(int id) {this.id = id;}
    @Override
    public String call() throws Exception { // 实现 call() 办法,而不是 run()
        return "result of TaskWithResult" + id;
 }
}
public class CallableDemo {public static void main(String[] args) {ExecutorService exec = Executors.newCachedThreadPool(); 
        ArrayList<Future<String>> results = new ArrayList<>(); //submit 办法会产生 Future 对象
        for (int i = 0; i < 10; i++) {results.add(exec.submit(new TaskWithResult(i)));// 必须应用 ExectorService.submit() 办法调用}
        for (Future<String> fs :
                results) {
            try {System.out.println(fs.get()); //get() 办法获取返回的后果,} catch (InterruptedException e) {System.out.println(e);
                return; 
            } catch (ExecutionException e) {System.out.println(e);
            }finally {exec.shutdown(); // 敞开
            }
        }
    }
}
  • 能够应用 Futrue 对象的 isDone() 办法来查问 Futrue 是否已实现
  • 也能够间接调用 get(),get() 办法会等到后果就绪后调用

优先级

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimplePriorities implements Runnable{
    private int countDown = 5;
 private volatile double d;
 private int priority;
 public SimplePriorities(int priority) {this.priority = priority;}
    public String toString(){return Thread.currentThread()+"优先级:"+priority + "计数" + ":"+countDown;
 }
    @Override
     public void run() {Thread.currentThread().setPriority(priority);
            while (true) {for (int i = 0; i < 100000; i++) {d += (Math.PI + Math.E) / (double) i;
                    if (i%1000==0) Thread.yield();}
            System.out.println(this);
            if (--countDown==0) return;
            }
     }
    public static void main(String[] args) {ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        }
        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        exec.shutdown();}
}

正文完
 0