编程问题中相当大的一部分都可以通过使用顺序编程来解决。然后,对于某些问题,如果能够并行的执行程序中的多个部分,则会变得非常方便甚至非常必要,因为这些部分要么看起来在并发地执行,要么在多处理器环境下可以同时执行,那么小伙们,你们知道在Java中怎么创建多线程么,一共有多少种方式呢?
我们今天就来聊一聊Java多线程的创建方式:
第一种,继承Thread类
public class TaskPollingMgr extends Thread{
public static void main(String[] args) {
TaskPollingMgr taskPollingMgr = new TaskPollingMgr();
taskPollingMgr.start();
}
@Override
public void run() {
int count=1;
int POPTASK_INTERVAL = 5;
while (true) {
exec();
count++;
if(count == 5){
count =0;
System.out.println(5/count);
}
try {
System.out.println(this.getName()+"线程运行时间"+new Date());
Thread.sleep(POPTASK_INTERVAL * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void exec(){
System.out.println("thread name="+this.getName());
}
}
第二种,实现Runnable接口
public class TaskQueueScheduler implements Runnable {
public static void main(String[] args) {
TaskQueueScheduler taskQueueScheduler = new TaskQueueScheduler();
Thread thread = new Thread(taskQueueScheduler,"TaskQueueSchedulerThread");
thread.start();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 线程启动"+" 启动时间=="+new Date());
int savePeriod = 5;
while (true) {
try {
Date currentTime = new Date();
if ((currentTime.getTime() / (1000 * 60)) % savePeriod == 0) {
System.out.println(Thread.currentThread().getName()+" 执行添加队伍列赶时间 currentTime=="+currentTime);
}
} catch (Exception e) {
e.printStackTrace();
continue;
} finally {
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
第三种,实现Callable接口
public class TestCallable implements Callable<Integer> {
public static void main(String[] args) {
try{
TestCallable tc = new TestCallable();
FutureTask<Integer> result = new FutureTask<>(tc);
Thread thread = new Thread(result,"TestCallable");
thread.start();
Integer sum = result.get(); //FutureTask 可用于 闭锁
System.out.println("返回结果:"+sum);
}catch (Exception ex){
ex.printStackTrace();
}
}
@Override
public Integer call() throws Exception {
System.out.println("当前线程名称:"+Thread.currentThread().getName());
return 1+ 2;
}
}
第四种,线程池
public class ThreadPerTaskExecutor implements Runnable {
public static void main(String[] args) {
try{
ExecutorService executors = Executors.newCachedThreadPool();
executors.execute(new ThreadPerTaskExecutor());
executors.shutdown();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println("线程方法被执行");
}
}
以上呢,就是JAVA多线程创建的常用方式,今天就先到这里,后续会再继续针对多线程的其它问题进行讲解。
欢迎大家入群交流,虫洞栈公众号的作者坐阵本群,有机会与大神面对面,赶紧来哦