先贴一张线程状态转换图再说:
1、创建的方式
- 继承Thread类;
- 实现Runnable接口;
- 匿名内部类实现方式;
- 带返回值的线程;
- 定时器;
- 线程池的实现;
- Lambda表达式实现;
- Spring创建多线程的方式。
2、代码演示
2.1 继承Thread类
代码:
package com.iflytek.demo.t1;
public class Demo1 extends Thread {
public Demo1(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) {
Demo1 d1 = new Demo1("xiancheng1");
Demo1 d2 = new Demo1("xiancheng2");
//d1.setDaemon(true); //创建守护线程
//d2.setDaemon(true);
d1.start();
d2.start();
//d1.stop(); //不推荐
d1.interrupt(); //线程中断销毁
}
}
运行结果:
xiancheng2线程执行了。。。
xiancheng2线程执行了。。。
xiancheng2线程执行了。。。
xiancheng2线程执行了。。。
xiancheng2线程执行了。。。
......
2.2 实现Runnable接口
代码:
package com.iflytek.demo.t1;
public class Demo2 implements Runnable {
@Override
public void run() {
while (true){
System.out.println("线程执行了。。。");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new Demo2());
thread.start();
}
}
运行结果:
线程执行了。。。
线程执行了。。。
线程执行了。。。
线程执行了。。。
线程执行了。。。
......
2.3 匿名内部类实现方式
代码:
package com.iflytek.demo.t1;
public class Demo3 {
public static void main(String[] args) {
//第一种方式
new Thread(){
@Override
public void run() {
System.out.println("方式一执行。。。");
System.out.println("==================================");
}
}.start();
//第二种方式
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("方式二执行。。。");
System.out.println("==================================");
}
}).start();
//放在一起的话呢??
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("(2)方式二执行。。。");
System.out.println("==================================");
}
}){
@Override
public void run() {
System.out.println("(1)方式一执行。。。");
System.out.println("==================================");
}
}.start();
}
}
运行结果:
方式一执行。。。
==================================
方式二执行。。。
==================================
(1)方式一执行。。。
==================================
2.4 带返回值的线程
代码:
package com.iflytek.demo.t1;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Demo4 implements Callable<Integer> {
public static void main(String[] args) throws Exception {
Demo4 demo4 = new Demo4();
//FutureTask类底层实现了Runnable接口
FutureTask<Integer> futureTask = new FutureTask<>(demo4);
Thread t = new Thread(futureTask);
t.start();
System.out.println("我先干点别的。。。");
Integer integer = futureTask.get();
System.out.println("计算结果为:"+integer);
}
@Override
public Integer call() throws Exception {
System.out.println("正在紧张的计算。。。");
Thread.sleep(3000);
return 1;
}
}
运算结果:
我先干点别的。。。
正在紧张的计算。。。
计算结果为:1
2.5 定时器
代码:
package com.iflytek.demo.t1;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Demo5 {
public static void main(String[] args) {
Timer timer = new Timer();
// 第一个参数:获取定时任务;
// 第二个参数:延迟多长时间;
// 第三个参数:每隔多长时间执行一下
timer.schedule(new TimerTask() { //抽象类,实现了Runnable接口
@Override
public void run() {
System.out.println("定时任务启动。。。");
}
},1000,1000);
}
}
运行结果:
定时任务启动。。。
定时任务启动。。。
定时任务启动。。。
定时任务启动。。。
定时任务启动。。。
定时任务启动。。。
......
2.6 线程池的实现
代码:
package com.iflytek.demo.t1;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo6 {
public static void main(String[] args) {
/***
* 案例一
*/
/*ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i=0;i<15;i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}*/
//停掉线程池
//threadPool.shutdown();
/***
* 案例二
*/
ExecutorService threadPool2 = Executors.newCachedThreadPool(); //智能创建线程
for (int i=0;i<15;i++) {
threadPool2.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
//停掉线程池
threadPool2.shutdown();
}
}
运行结果:
案例一运行结果:
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-2
pool-1-thread-1
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-4
pool-1-thread-7
pool-1-thread-9
pool-1-thread-5
pool-1-thread-6
pool-1-thread-8
pool-1-thread-10
案例二运行结果:
pool-1-thread-2
pool-1-thread-1
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-4
pool-1-thread-2
pool-1-thread-6
pool-1-thread-10
pool-1-thread-1
pool-1-thread-3
pool-1-thread-7
pool-1-thread-9
pool-1-thread-11
pool-1-thread-8
2.7 使用Lambda表达式实现多线程
代码:
package com.iflytek.demo.t1;
import java.util.Arrays;
import java.util.List;
public class Demo7 {
public int add(List<Integer> values){
System.out.println("无序遍历集合中的值为:");
//forEach进行无序遍历
values.parallelStream().forEach(System.out :: println);
System.out.println("有序遍历集合中的值为:");
//forEachOrdered进行有序遍历
values.parallelStream().forEachOrdered(System.out :: println);
return values.parallelStream().mapToInt(i -> i).sum();
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10,20,30,40);
int add = new Demo7().add(list);
System.out.println("求和的结果为:"+add);
}
}
运行结果:
无序遍历集合中的值为:
30
40
10
20
有序遍历集合中的值为:
10
20
30
40
求和的结果为:100
2.8 Spring创建多线程的方式
注意:需要引入Spring相关的依赖,这里我就不描述了,直接看代码。
代码:
1、首先创建Spring相关配置类Config:
package com.iflytek.test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@ComponentScan("com.iflytek.test")
@EnableAsync
public class Config {
}
2、然后创建多线程任务类DemoService:
package com.iflytek.test;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Async
public void aVoid() {
while (true) {
System.out.println("Thread a...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Async
public void bVoid() {
while (true) {
System.out.println("Thread b...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3、最后创建一个启动类Main:
package com.iflytek.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
DemoService bean = ac.getBean(DemoService.class);
bean.aVoid();
bean.bVoid();
}
}
运行结果: 每隔两秒钟会输出一组a和b的输出语句;这样就实现了多线程。
Thread a...
Thread b...
Thread b...
Thread a...
Thread b...
Thread a...
Thread a...
Thread b...
Thread b...
......