创建线程的方式可以有以下几种:
- 继承Thread类
- 实现Runnable接口
- 匿名内部类的方式
- 带返回值的线程
- 定时器
- 线程池的实现
- Spring的线程实现
- Lambda表达式实现
继承Thread类(创建运行并中断)
//Demo1本身是一个Thread,可以直接new Demo1
public class Demo1 extends Thread{
public Demo1(String name) {
super(name);
}
@Override
public void run() {
while(!isInterrupted()){
System.out.println(getName()+"线程运行了。。。");
}
}
public static void main(String[] args) {
Demo1 d1 = new Demo1("first-thread");
Demo1 d2 = new Demo1("second-thread");
d1.start();
d2.start();
//d2.stop(); stop()只是让线程进入无休止的等待,并没有释放锁等资源 ,已废弃
d2.interrupt();//interrupt()会等run执行完安全地中断线程,释放资源
}
}
实现Runnable接口
public class newThread implements Runnable{
@Override
public synchronized void run() {
while(true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程启动了。。。");
}
}
public static void main(String[] args) {
newThread thread = new newThread();
Thread n = new Thread(thread);
n.start();
while(true){
synchronized(thread){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程启动了。。。");
thread.notifyAll();
}
}
}
}
匿名内部类的方式
//如果线程只执行一次,没必要创建类来创建线程
public class Demo3 {
public static void main(String[] args) {
//Thread子类
new Thread(){
public void run() {
System.out.println("sub");
};
}.start();
//Runnable
new Thread(new Runnable(){
@Override
public void run() {
System.out.println("runnable");
}
}).start();
}
}
带返回值的线程
public class Demo4 implements Callable<Integer>{
public static void main(String[] args) throws InterruptedException, ExecutionException {
Demo4 d4 = new Demo4();
//封装带返回值的Callable为Runnable任务,call()相当于run()
FutureTask<Integer> task = new FutureTask<>(d4);
Thread thread = new Thread(task);
thread.start();
System.out.println("先做点别的。。。。");
Integer result = task.get();
System.out.println("执行结果为"+result);
}
//返回整型
@Override
public Integer call() throws Exception {
System.out.println("正在计算。。。");
Thread.sleep(3000);
return 1;
}
}
定时器
timer不是很灵活,常用的一个框架是quartz
//相当于开辟一个线程执行定时任务
public class Demo5 {
public static void main(String[] args) {
Timer timer = new Timer();
//TimerTask实现了Runnable接口
timer.schedule(new TimerTask(){
@Override
public void run() {
System.out.println("定时任务执行。。。");
}
}, 0, 1000);
}
}
线程池的实现
//从线程池取线程,用完放回线程池,减少线程创建销毁的资源消耗(拿空间换时间)
public class Demo6 {
public static void main(String[] args) {
//newCachedThreadPool智能创建和回收线程,不够用就创建,够用就回收
ExecutorService threadPool = Executors.newCachedThreadPool();
for(int i=0;i<100;i++){
threadPool.execute(new Runnable(){
@Override
public void run() { System.out.println(Thread.currentThread().getName());
}
});
}
threadPool.shutdown();
}
}
spring实现多线程
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Config.java:
@Configuration
@ComponentScan("com.test.thread.t1")
@EnableAsync
public class Config {
}
DemoService.java:
@Service
public class DemoService {
@Async
public void a(){
while(true){
System.out.println("a");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Async
public void b(){
while(true){
System.out.println("b");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Main.java:
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
DemoService ds = ac.getBean(DemoService.class);
ds.a();
ds.b();
}
}
lambda表达式实现
public class Demo7 {
public static void main(String[] args) {
List<Integer> values = Arrays.asList(10,20,30,40);
int res = new Demo7().add(values);
System.out.println("计算结果为:"+res);
}
public int add(List<Integer> values){
values.parallelStream().forEach(System.out :: println);//并行遍历是无序的
return values.parallelStream().mapToInt(i -> i).sum();
}
}