java猜数游戏
发布网友
发布时间:2022-05-08 01:15
我来回答
共2个回答
热心网友
时间:2023-11-23 04:58
//线程调用创建主类
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 CallableTest {
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// 线程池
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable<String> c1 = new CallableThread("线程1");
Callable<String> c2 = new CallableThread("线程2");
while(true){
// 表示异步计算的结果
Future<String> f1 = pool.submit(c1);
Future<String> f2 = pool.submit(c2);
if("100".equals(f1.get())||"100".equals(f2.get())){
// 关闭线程池
pool.shutdown();
break;
}
}
}
}
//线程计算类
import java.util.concurrent.Callable;
public class CallableThread implements Callable<String> {
private String str;
public CallableThread(String str) {
this.str = str;
}
// 需要实现Callable的Call方法
public String call() throws Exception {
int num = 0;
for (int j = 0; j < 10; j++) {
num += (int)(Math.random() * 30)+3;
}
String strnum = ""+num;
System.out.println(str+":"+strnum);
return strnum;
}
}
--如果可以,望采纳
热心网友
时间:2023-11-23 04:58
可以的
热心网友
时间:2023-11-23 04:58
//线程调用创建主类
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 CallableTest {
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// 线程池
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable<String> c1 = new CallableThread("线程1");
Callable<String> c2 = new CallableThread("线程2");
while(true){
// 表示异步计算的结果
Future<String> f1 = pool.submit(c1);
Future<String> f2 = pool.submit(c2);
if("100".equals(f1.get())||"100".equals(f2.get())){
// 关闭线程池
pool.shutdown();
break;
}
}
}
}
//线程计算类
import java.util.concurrent.Callable;
public class CallableThread implements Callable<String> {
private String str;
public CallableThread(String str) {
this.str = str;
}
// 需要实现Callable的Call方法
public String call() throws Exception {
int num = 0;
for (int j = 0; j < 10; j++) {
num += (int)(Math.random() * 30)+3;
}
String strnum = ""+num;
System.out.println(str+":"+strnum);
return strnum;
}
}
--如果可以,望采纳
热心网友
时间:2023-11-23 04:58
可以的