这一章节我们来讨论一下线程的返回与sleep。
1.线程的返回
package com.ray.ch17;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
ExecutorService executors = Executors.newFixedThreadPool(2);
Callable<Integer> callable = new MyCall();
for (int i = 0; i < 10; i++) {
Future<Integer> future = executors.submit(callable);
System.out.println(future.get());
}
}
}
class MyCall implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("doing something...");
Thread.sleep(1000);
return new Random().nextInt(50);
}
}
输出:
doing something...
34
doing something...
2
doing something...
10
doing something...
11
doing something...
10
doing something...
28
doing something...
21
doing something...
29
doing something...
25
doing something...
0
上面的其实之前的一篇文章:从头认识java-17.6 Callable、Future和FutureTask里面所说的内容。
2.sleep
如果大家运行上面的代码,就会明显的感觉到每输出一遍,都会有停顿,这个就是sleep的作用。
总结:这一章节主要说明了线程的返回与sleep。
这一章节就到这里,谢谢。
-----------------------------------