1.多线程的四种实现方式
1)继承Thread类
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();
}
class MyThread extends Thread {
public void run() {
System.out.println("MyThread.run()");
}
}
2)实现Runnable接口
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
output.output("zhangxiaoxiang");
}
}
}).start();
3)实现Callable接口
public static void main(String[] args){
ExecutorService executorService=Executors.newFixedThreadPool(3);
try{
Future<String> future=executorService.submit(new MyCallable());
System.out.println(future.get());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "hello";
}
}
4)通过FutureTask包装器
public static void main(String[] args) { // //创建线程池
// ExecutorService es = Executors.newSingleThreadExecutor();
// //创建Callable对象任务
// CallableDemo calTask=new CallableDemo();
// //提交任务并获取执行结果
// Future<Integer> future =es.submit(calTask);
// //关闭线程池
// es.shutdown();
//创建线程池
ExecutorService es = Executors.newSingleThreadExecutor();
//创建Callable对象任务
CallableDemo calTask=new CallableDemo();
//创建FutureTask
FutureTask<Integer> futureTask=new FutureTask<>(calTask);
//执行任务
es.submit(futureTask);
//关闭线程池
es.shutdown();
try {
Thread.sleep(2000);
System.out.println("主线程在执行其他任务");
if(futureTask.get()!=null){
//输出获取到的结果
System.out.println("futureTask.get()-->"+futureTask.get());
}else{
//输出获取到的结果
System.out.println("futureTask.get()未获取到结果");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("主线程在执行完成");
}
}
网友评论