创建线程的多种方式
- 继承Thread类
package com.yrz;
public class ExtendsThread extends Thread {
public ExtendsThread(String name) {
super(name);
}
@Override
public void run() {
while (!interrupted()) {
System.out.println(getName() + "线程执行了 .. ");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExtendsThread d1 = new ExtendsThread("first-thread");
ExtendsThread d2 = new ExtendsThread("second-thread");
d1.start();
d2.start();
d1.interrupt(); }}
- 实现Runnable接口
package com.yrz;
public class ImpRunnable implements Runnable{
@Override
public void run() {
while (true)
System.out.println("thread start");
}
public static void main(String args[]){
Thread t = new Thread(new ImpRunnable());
t.start();
}
}
- 匿名内部类的方式
package com.yrz;
public class innerThread {
public static void main(String args[]){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("匿名内部类的方式实现线程");
}
}).start();
}
}
- 带返回值的线程
package com.yrz;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ReturnThread implements Callable {
public static void main(String args[]){
ReturnThread run = new ReturnThread();
FutureTask<String> future =new FutureTask<>(run);
Thread t=new Thread(future);
t.start();
String res = null;
try {
res = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("------"+res);
}
@Override
public String call() throws Exception {
return "带有返回值的线程创建";
}
}
- 定时器(quartz)
package com.yrz;
import java.util.Timer;
import java.util.TimerTask;
public class QuartzThread extends TimerTask {
@Override
public void run() {
System.out.println("timertask is run");
}
public static void main(String args[]) {
Timer timer = new Timer();
QuartzThread quartzThread = new QuartzThread();
quartzThread.run();
timer.schedule(quartzThread, 0, 1000);
}
}
- 线程池的实现
package com.yrz;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Executor {
public static void main(String args[]) {
ExecutorService CacExecutorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
CacExecutorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
运行结果
pool-1-thread-1
pool-1-thread-5
pool-1-thread-2
pool-1-thread-4
pool-1-thread-3
ExecutorService SigExecutorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
SigExecutorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
运行结果
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
ExecutorService fixExecutorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
fixExecutorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
}
}
运行结果
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-1
pool-1-thread-3
- Lambda表达式实现
package com.yrz;
import java.util.Arrays;
import java.util.List;
public class Lambda {
public static void main(String args[]) {
List<Integer> list = Arrays.asList(10, 30, 40, 20);
System.out.println("计算结果" + new Lambda().add(list));
}
public int add(List<Integer> values) {
return values.parallelStream().mapToInt(i -> i).sum();
}
}
运行结果
计算结果100
- Spring实现多线程
- ThreadConfig 实现AsyncConfigurer 异步接口,创建线程池
- AsynTaskService 具体要创建异步任务
- 创建main函数测试
package com.yrz;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@ComponentScan("com.yrz")
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
package com.yrz;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Random;
import java.util.UUID;
@Service
public class AsynTaskService {
@Async
public void f1() {
System.out.println("f1 : " + Thread.currentThread().getName() + " " + UUID.randomUUID().toString());
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Async
public void f2() {
System.out.println("f2 : " + Thread.currentThread().getName() + " " + UUID.randomUUID().toString());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import com.yrz.AsynTaskService;
import com.yrz.ThreadConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String agrs[]) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ThreadConfig.class);
AsynTaskService service = context.getBean(AsynTaskService.class);
for (int i = 0; i < 10; i++) {
service.f1();
service.f2();
}
context.close();
}
}
运行结果:
ThreadPoolTaskExecutor-1 bd535a93-4fdd-4e50-b027-9182dea4ff5a f1
ThreadPoolTaskExecutor-5 f118ed63-2dee-493a-9326-e2d4b71c5c11 f2
ThreadPoolTaskExecutor-2 c9c1d664-e6d1-4d93-8a56-67dbeba823cb f2
ThreadPoolTaskExecutor-4 fefba07d-4361-4f06-b844-28210c087322 f1
ThreadPoolTaskExecutor-3 e90d7e28-bfbf-4588-b3b9-8cc41ae5cb74 f2
ThreadPoolTaskExecutor-3 c98dbd8c-b948-4aa3-9635-9fd552853533 f1
ThreadPoolTaskExecutor-1 62f06e34-1ae5-4aba-bacb-0bf2872f051e f2