java多线程都有几种方式实现 (转)
有三种:
(1)继承Thread类,重写run函数
创建:
- <span style="font-size: 12px;">class xx extends Thread{
- public void run(){
- Thread.sleep(1000) //线程休眠1000毫秒,sleep使线程进入Block状态,并释放资源
- }}</span>
class xx extends Thread{
public void run(){
Thread.sleep(1000) //线程休眠1000毫秒,sleep使线程进入Block状态,并释放资源
}}
开启线程:
对象.start() //启动线程,run函数运行
(2)实现Runnable接口,重写run函数
开启线程:
- <span style="font-size: 12px;"> Thread t = new Thread(对象) //创建线程对象
- t.start()</span>
Thread t = new Thread(对象) //创建线程对象
t.start()
(3)实现Callable接口,重写call函数
Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
Callable和Runnable有几点不同:
①Callable规定的方法是call(),而Runnable规定的方法是run().
②Callable的任务执行后可返回值,而Runnable的任务是不能返回值的
③call()方法可抛出异常,而run()方法是不能抛出异常的。
④运行Callable任务可拿到一个Future对象,Future表示异步计算的结果。它提供了检查计算是否完成的方法,以等
待计算的完成,并检索计算的结果.通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果
Java Callable 代码示例:
- class TaskWithResult implements Callable<String> {
- private int id;
- public TaskWithResult(int id) {
- this.id = id;
- }
- @Override
- public String call() throws Exception {
- return "result of TaskWithResult " + id;
- }
- }
- public class CallableTest {
- public static void main(String[] args) throws InterruptedException,
- ExecutionException {
- ExecutorService exec = Executors.newCachedThreadPool();
- ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future 相当于是用来存放Executor执行的结果的一种容器
- for (int i = 0; i < 10; i++) {
- results.add(exec.submit(new TaskWithResult(i)));
- }
- for (Future<String> fs : results) {
- if (fs.isDone()) {
- System.out.println(fs.get());
- } else {
- System.out.println("Future result is not yet complete");
- }
- }
- exec.shutdown();
- }
- }
class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public String call() throws Exception { return "result of TaskWithResult " + id; } } public class CallableTest { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future 相当于是用来存放Executor执行的结果的一种容器 for (int i = 0; i < 10; i++) { results.add(exec.submit(new TaskWithResult(i))); } for (Future<String> fs : results) { if (fs.isDone()) { System.out.println(fs.get()); } else { System.out.println("Future result is not yet complete"); } } exec.shutdown(); } }
运行结果:
result of TaskWithResult 0
result of TaskWithResult 1
result of TaskWithResult 2
result of TaskWithResult 3
result of TaskWithResult 4
result of TaskWithResult 5
result of TaskWithResult 6
result of TaskWithResult 7
result of TaskWithResult 8
result of TaskWithResult 9
上一篇: 可以获得结果的线程