java 多线程编程三种实现方式

时间:2023-03-09 16:21:01
java 多线程编程三种实现方式

一种是继承Thread类,一种是实现Runable接口,还有一种是实现callable接口;

有博主说只有前面2种方式,我个人愚见是三种,主要详细介绍下callable的使用;

三种线程的我的个人理解:

thread 是最简单的,简单粗暴也是最基础的,复写run()方法,start启动就好了;

runable 是thread基础上的改进版本runable 主要的贡献在于实现了资源的共享,比如说在线选座的座位资源就需要共享这个时候就一定要使用runable,但是他也需要thread 的帮忙;

callable 是主要用来处理异步,线程本身是消耗时间资源的所以,你有时候需要等他的处理结果,这个时候就需要callable;

匿名threadable的创建使用方式;

new Thread()

{

@Override

public void run()

{

// TODO Auto-generated method stub

// do something here

}

}.start();

匿名runable的创建使用方式

new Thread(new Runnable()

{

@Override

public void run()

{

// TODO Auto-generated method stub

// do something here

}

}).start();

callable的创建使用方式

public class CallableTest{

/**

测试案例是远程异步解密;

*/

public String decryption(String _ciphertext) {

String result = "";

// 创建一个线程池

ExecutorService pool = Executors.newFixedThreadPool(2);

Callable c = new CallableTest();

// 执行任务并获取Future对象

Future f = pool.submit(c);//配合使用拿数据的

// 关闭线程池

pool.shutdown();

try {

result = f.get().toString();

} catch (InterruptedException e) {

result = "";

} catch (ExecutionException e) {

result = "";

}

return result;

}

@SuppressWarnings("rawtypes")

class CallableTest implements Callable {

//区别于另两个线程的方式这里复写call()方法

public String call() throws Exception {

// please dosomething   here;

}

}

}