码迷,mamicode.com
首页 > 编程语言 > 详细

Java的三种多线程

时间:2017-06-13 18:21:11      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:integer   tar   exce   java   cal   src   cep   print   ble   

项目结构

技术分享

继承Thread类

/*
 * Thread类实现了Runnable接口
 */

public class MyThread extends Thread {
    @Override
    public void run() {
        for(int i=0;i<50;i++){
            System.out.println("MyThread子线程 : "+Thread.currentThread().getName()+"~~~"+i);
        }
    }
}

 

实现Runnable接口

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        for(int i=0;i<50;i++){
            System.out.println("MyRunnable子线程 : "+Thread.currentThread().getName()+"~~~"+i);
        }
    }

}

 

实现Callable<T>接口

import java.util.concurrent.Callable;
/*
 * FutureTask<V>类实现了RunnableFuture<V>接口,
 * RunnableFuture<V>接口实现了Runnable接口、Future<V>接口。
 * FutureTask<V>对象的get方法:等待计算完成,然后获取其结果。
 */

public class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for(int i=0;i<100;i++){
            sum += i;
            System.out.println("MyCallable子线程中间结果 : "+sum);
        }
        return sum;
    }

}

运行

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


public class Test {

    public static void main(String[] args) throws Exception {
        System.out.println("主线程 : "+Thread.currentThread().getName());
        MyThread thread = new MyThread();
        MyRunnable runnable = new MyRunnable();
        Thread thread2 = new Thread(runnable);
        MyCallable callable = new MyCallable();
        FutureTask<Integer> task = new FutureTask<Integer>(callable);
        Thread thread3 = new Thread(task);
        thread.start();
        thread2.start();
        thread3.start();
        int sum = task.get();
        System.out.println("MyCallable子线程最终结果 : " + sum); // 这段代码总是最后执行
    }

}

 

Java的三种多线程

标签:integer   tar   exce   java   cal   src   cep   print   ble   

原文地址:http://www.cnblogs.com/sea-breeze/p/7002622.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!