当前位置: 首页>后端>正文

JUC基础:Callable案例

JUC基础:Callable案例,第1张

public class MyCallable2 {

public static void main(String[] args) throws ExecutionException, InterruptedException {

// SpringMVC模拟效果!

// (1)单线程

// ???????long a = System.currentTimeMillis();

// ???????Service1 s1 = new Service1();

// ???????Service2 s2 = new Service2();

// ???????Service3 s3 = new Service3();

// ???????System.out.println(s1.m1());

// ???????System.out.println(s2.m2());

// ???????System.out.println(s3.m3());

// ???????System.out.println(System.currentTimeMillis() - a);

// (2)多线程

Callable callable = new Callable() {

@Override

public Object call() throws Exception {

Service1 s1 = new Service1();

return s1.m1();

}

};

FutureTask<String> futureTask = new FutureTask<>(callable);

new Thread(futureTask).start();

String s = futureTask.get();// 主线程会大量阻塞、等待到有结果出来

System.out.println(s);

Callable callable2 = new Callable() {

@Override

public Object call() throws Exception {

Service2 s2 = new Service2();

return s2.m2();

}

};

FutureTask<String> futureTask2 = new FutureTask<>(callable2);

new Thread(futureTask2).start();

String s2 = futureTask2.get();// 主线程会大量阻塞、等待到有结果出来

System.out.println(s2);

Callable callable3 = new Callable() {

@Override

public Object call() throws Exception {

Service3 s3 = new Service3();

return s3.m3();

}

};

FutureTask<String> futureTask3 = new FutureTask<>(callable3);

new Thread(futureTask3).start();

String s3 = futureTask3.get();// 主线程会大量阻塞、等待到有结果出来

System.out.println(s3);

}

}

class Service1 {

String m1() {

return "查询用户信息";

}

}

class Service2 {

String m2() {

return "查询余额信息";

}

}

class Service3 {

String m3() {

return "查询积分信息";

}

}


https://www.xamrdz.com/backend/36s1941223.html

相关文章: