JAVA实现多线程的四种方式
Posted Covenant
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA实现多线程的四种方式相关的知识,希望对你有一定的参考价值。
1.继承Thread类
public class myThread extends Thread{
@Override
public void run() {
System.out.println("现在的线程是:"+Thread.currentThread());
}
public static void main(String[] args) {
new myThread().start();
new myThread().start();
new myThread().start();
}
}
2.实现Runnable接口
public class myRunnable implements Runnable{
@Override
public void run() {
System.out.println("现在的线程是:"+Thread.currentThread());
}
public static void main(String[] args) {
new Thread(new myRunnable()).start();
new Thread(new myRunnable()).start();
new Thread(new myRunnable()).start();
}
}
3.实现Callable接口并用FutureTask包装
public class MyCallAble implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("现在的线程是:"+Thread.currentThread());
return null;
}
public static void main(String[] args) {
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
new Thread(new FutureTask<>(new MyCallAble())).start();
}
}
4.利用Executor类返回的线程
public class ExcutorPool {
public static void main(String[] args) throws Exception{
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Integer>> list=new ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) {
Future<Integer> future=pool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
System.out.println("当前线程为"+Thread.currentThread());
return null;
}
});
list.add(future);
}
//关闭线程池
pool.shutdown();
for (Future<Integer> future : list) {
//此处输出线程结束后的返回值future.get();
}
}
}
以上是关于JAVA实现多线程的四种方式的主要内容,如果未能解决你的问题,请参考以下文章