文章目录
一,线程,进程,多线程
(1)多任务
(2)多线程
(3)普通方法调用和多线程
(4)程序,进程,线程
(5)线程与进程
(6)小结
二,线程创建
(1)三种创建方式
(2)Thread
注意:线程开启不一定立即执行,由CPU调度执行
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//主线程和子线程并行交替执行
public class Thread1 extends Thread {
@Override
public void run() {
//run方法线程体
for(int i=0;i<10;i++){
System.out.println("run方法线程体"+i);
}
}
public static void main(String[] args) {
//创建一个线程对象,并调用start()方法开启线程
Thread1 thread1=new Thread1();
thread1.start();
//main线程,主线程
for(int i=0;i<100;i++){
System.out.println("main线程,主线程"+i);
}
}
}
(3)Runnable
//创建线程方式2:实现Runnable接口,重写run方法,执行线程需要丢入Runnable接口实现类,调用start开启线程
public class Thread2 implements Runnable {
@Override
public void run() {
//run方法线程体
for(int i=0;i<10;i++){
System.out.println("run方法线程体"+i);
}
}
public static void main(String[] args) {
//创建Runnable接口的实现类对象
Thread2 thread2=new Thread2();
//创建线程对象,通过线程对象来开启我们的线程,代理
Thread thread=new Thread(thread2);
thread.start();
//main线程,主线程
for(int i=0;i<100;i++){
System.out.println("main线程,主线程"+i);
}
}
}
(4)小结
//多个线程同时操作同一个对象
//买火车票问题
public class Thread2Test implements Runnable{
private int ticketNums=10;//票数
@Override
public void run() {
while(true){
if(ticketNums<=0){
break;
}
//模拟延时
try{
Thread.sleep(250);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
Thread2Test ticket=new Thread2Test();
new Thread(ticket,"王某").start();
new Thread(ticket,"张三").start();
new Thread(ticket,"小黄牛").start();
}
}
并发问题:
//模拟龟兔赛跑
public class Thread2Test1 implements Runnable {
private static String winner;//胜利者
@Override
public void run() {
for(int i=0;i<=100;i++){
//模拟兔子休息
if(Thread.currentThread().getName().equals("兔子")&&i%10==0){
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag=gameOver(i);
//如果比赛结束就退出
if(flag) break;
System.out.println(Thread.currentThread().getName()+"跑了-->"+i+"步");
}
}
private boolean gameOver(int steps) {
//判断是否有胜利者
if(winner!=null){//已经存在胜利者
return true;
}else{
if(steps>=100){
winner=Thread.currentThread().getName();
System.out.println("winner is"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Thread2Test1 race=new Thread2Test1();
new Thread(race,"兔子").start();
new Thread(race,"大乌龟").start();
}
}
(5)Callable
//线程创建方式三:实现Callable接口 好处:可以定义返回值,可以抛出异常
public class CallableTest implements Callable<Boolean> {
private String url;//网络图片地址
private String name;//保存的文件名
public CallableTest(String url,String name){
this.url=url;
this.name=name;
}
@Override
public Boolean call() throws Exception {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了图片的文件名为:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableTest thread1Test1=new CallableTest("http://222.186.12.235:41001/Uploads/vod/2021-02-03/601a19c71e562.jpg","窥探1.jpg");
CallableTest thread1Test2=new CallableTest("http://pic.baike.soso.com/p/20110826/20110826220618-1504115653.jpg","窥探2.jpg");
CallableTest thread1Test3=new CallableTest("https://p0.itc.cn/images01/20210423/a454b56b139e433c81cf2f1aaad2ae7a.png","窥探3.jpg");
//创建执行服务
ExecutorService service= Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1=service.submit(thread1Test1);
Future<Boolean> r2=service.submit(thread1Test2);
Future<Boolean> r3=service.submit(thread1Test3);
//获取结果
boolean res1=r1.get();
boolean res2=r2.get();
boolean res3=r3.get();
//关闭服务
service.shutdownNow();
}
}
三,静态代理
/**
* 静态代理模式总结:真实对象和代理对象都要实现同一个接口,代理对象要代理真实角色
* 好处:代理对象可以做很多真实对象做不了的事情,真实对象专注做自己事情
*/
public class StaticProxy {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("静态代理:");
}
}).start();
WeddingCompany weddingCompany=new WeddingCompany(new My());
weddingCompany.HappyMarry();
}
}
//真实角色,我去结婚
class My implements Marry{
@Override
public void HappyMarry() {
System.out.println("王某要结婚啦,😊");
}
}
interface Marry{
void HappyMarry();
}
//代理角色,帮助我结婚
class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry target){
this.target=target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();
after();
}
private void before() {
System.out.println("结婚之前,婚庆公司布置现场");
}
private void after() {
System.out.println("结婚之后,婚庆公司收钱");
}
}
四---------》七
四---------》七 |
---|
线程状态和方法 |
四,线程五大状态
(1)线程状态
(2)线程方法
(3)线程停止
1,停止线程
2,代码
/**
* 测试stop:
* 1,建议线程正常停止-->利用次数,不建议死循环
* 2,建议使用标记位-->设置一个标记位
* 3,不要使用stop或者destroy等过时或者JDK不建议使用的方法
*/
public class StopTest implements Runnable{
//1,设置一个标记位
private boolean flag=true;
@Override
public void run() {
int i=0;
while(flag){
System.out.println("run........Thread"+i++);
}
}
//2,设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
StopTest stopTest=new StopTest();
new Thread(stopTest).start();
for(int i=0;i<=100;i++){
System.out.println("main"+i);
if(i==90){
//调用stop方法切换标志位,让线程停止
stopTest.stop();
System.out.println("该线程停止啦");
}
}
}
}
(4)线程休眠–sleep
1,线程休眠
2,模拟网络延时
//模拟网络延时:放大问题的发生性
public class SleepTest implements Runnable{
private int ticketNums=10;//票数
@Override
public void run() {
while (true) {
if (ticketNums <= 0) {
break;
}
//模拟延时
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums-- + "张票");
}
}
public static void main(String[] args) {
SleepTest ticket=new SleepTest();
new Thread(ticket,"王某").start();
new Thread(ticket,"张三").start();
new Thread(ticket,"小黄牛").start();
}
}
3,模拟倒计时
//模拟倒计时。。。
public class SleepTest2 {
public static void main(String[] args) {
//打印当前系统时间
Date startTime=new Date(System.currentTimeMillis());//获取系统当前时间
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime=new Date(System.currentTimeMillis());//更新当前时间
}
}
public static void tenDown() throws InterruptedException{
int num=10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
(5)线程礼让–yield
1,线程礼让
2,代码
//测试礼让线程,礼让不一定成功,看CPU心情
public class YieldTest {
public static void main(String[] args) {
MyYield myYield=new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
3,礼让成功
(6)线程强制执行–join
1,join
2,代码
//测试join方法,想象为插队
public class JoinTest implements Runnable {
@Override
public void run() {
for(int i=0;i<1000;i++){
System.out.println("线程VIP来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动线程
JoinTest joinTest=new JoinTest();
Thread thread=new Thread(joinTest);
thread.start();
//主线程
for(int i=0;i<500;i++){
if(i==200){
thread.join();
}
System.out.println("main"+i);
}
}
}
五,线程状态观测
(1)线程状态
//线程状态的观察测试
public class StateTest {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
for(int i=0;i<=5;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("~~~~~~~~~~~~~~~");
});
//观察状态
Thread.State state=thread.getState();
System.out.println(state); //NEW
//观察启动后
thread.start();//启动线程
state=thread.getState();
System.out.println(state); //Run
while(thread.getState()!=Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state=thread.getState();
System.out.println(state);//输出状态
}
}
}
六,线程的优先级
(1),线程优先级Priority
(2),优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度
(3),代码
//测试线程优先级
public class PriorityTest {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
MyPriority myPriority=new MyPriority();
Thread thread1=new Thread(myPriority);
Thread thread2=new Thread(myPriority);
Thread thread3=new Thread(myPriority);
Thread thread4=new Thread(myPriority);
//先设置优先级,再启动
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY);
thread4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
七,守护线程
(1),daemon
(2),代码
//测试守护线程
public class DaemonTest {
public static void main(String[] args) {
God god=new God();
Me me=new Me();
Thread thread=new Thread(god);
thread.setDaemon(true);//默认false表示式用户线程,正常的线程都是用户线程
thread.start();
new Thread(me).start();//用户线程启动
}
}
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("上帝保佑我");
}
}
}
class Me implements Runnable{
@Override
public void run() {
for(int i=0;i<=365;i++){
System.out.println("美好的一天开始了");
}
System.out.println("~~~~~~~~~~~~~goodbye~~~~~~~~~~~~~~");
}
}
八,线程同步机制
(1)多个线程操作同一个资源
(2)线程同步
(3)队列和锁
线程同步安全性
(4)synchronized
(5)不安全案例
1,不安全案例–买票
//不安全的买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket ticket=new BuyTicket();
new Thread(ticket,"王某").start();
new Thread(ticket,"张三").start();
new Thread(ticket,"小黄牛").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums=10;//票
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while(flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到第"+ticketNums--+"张票");
}
}
2,不安全案例–取钱
//不安全的取钱,两个人去一行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account=new Account(100,"结婚基金");//账户
Take me=new Take(account,50,"我");
Take girlFriend=new Take(account,100,"某某某");
me.start();
girlFriend.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money,String name){
this.money=money;
this.name=name;
}
}
//银行,模拟取款
class Take extends Thread{
Account account;//账户
int takeMoney;//取了多少钱
int nowMoney;//现在手里有多少钱
public Take(Account account,int takeMoney,String name){
super(name);
this.account=account;
this.takeMoney=takeMoney;
}
//取钱
@Override
public void run() {
//判断有没有钱
if(account.money-takeMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额-取的钱
account.money=account.money-takeMoney;
//现在手里的钱
nowMoney=nowMoney+takeMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(Thread.currentThread().getName()+"手里的钱:"+nowMoney);
}
}
3,不安全案例–线程不安全的集合
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
for(int i=0;i<=10000;i++){
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
4,线程不安全来源–》线程的内存是各自的,互不影响
每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
5,同步方法及同步块
<1>同步方法
<2>同步方法弊端
<3>synchronized同步方法保证安全买票
<4>同步块
锁的对象就是变化的量,需要增删改的对象
//银行,模拟取款
class Take extends Thread{
Account account;//账户
int takeMoney;//取了多少钱
int nowMoney;//现在手里有多少钱
public Take(Account account,int takeMoney,String name){
super(name);
this.account=account;
this.takeMoney=takeMoney;
}
//取钱
//synchronized默认锁的是this
@Override
public void run() {
synchronized(account){
//判断有没有钱
if(account.money-takeMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额-取的钱
account.money=account.money-takeMoney;
//现在手里的钱
nowMoney=nowMoney+takeMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(Thread.currentThread().getName()+"手里的钱:"+nowMoney);
}
}
}
<5>synchronized同步块保证集合安全
public class UnsafeList {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
for(int i=0;i<=10000;i++){
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
九,JUC
https://www.bilibili.com/video/BV1B7411L7tE?from=search&seid=9216133184325797901
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class JUCTest {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
十,死锁
1,死锁问题
多个线程互相抱着对方需要的资源,然后形成僵持
2,代码
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup girl1=new Makeup(0,"阿巴0");
Makeup girl2=new Makeup(1,"欧尼酱1");
girl1.start();
girl2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick=new Lipstick();
static Mirror mirror=new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
Makeup(int choice,String girlName){
this.choice=choice;
this.girlName=girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException{
if(choice==0){
synchronized(lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
synchronized(mirror){//一秒钟后想获得镜子
System.out.println(this.girlName+"获得镜子的锁");
}
}
}else{
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(1000);
synchronized(lipstick){//一秒钟想获得口红
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
}
3,死锁现象
4,死锁解决
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException{
if(choice==0){
synchronized(lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized(mirror){//一秒钟后想获得镜子
System.out.println(this.girlName+"获得镜子的锁");
}
}else{
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(1000);
}
synchronized(lipstick){//一秒钟想获得口红
System.out.println(this.girlName+"获得口红的锁");
}
}
}
5,死锁避免条件
十一,Lock锁
(1)Lock
(2)ReentrantLock详解:ReentrantLock一个可重入的互斥锁,又称为“独占锁”;ReentrantLock锁在同一个时间点只能被一个线程锁持有;而可重入的意思是,ReentrantLock锁,可以被单个线程多次获取;ReentrantLock在同一个时间点只能被一个线程获取
https://blog.csdn.net/SunStaday/article/details/107451530
(3)ReentrantLock代码
//买票测试Lock锁
public class LockTest {
public static void main(String[] args) {
LockTest2 lockTest2=new LockTest2();
new Thread(lockTest2).start();
new Thread(lockTest2).start();
new Thread(lockTest2).start();
}
}
class LockTest2 implements Runnable{
int ticketNums=10;
//定义lock锁
private final ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while(true){
try{
lock.lock();//加锁
if(ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else{
break;
}
}finally {
lock.unlock();//释放锁
}
}
}
}
(4)Lock与synchronized的比较
十二,线程通信
(1)线程协作—生产者消费者问题
(2)线程通信应用场景
(3)线程通信分析
生产者生产,消费者消费,两条线程之间可以通信
(4)解决线程通信的方法
(5)解决方式一–管程法
1,管程法–利用缓冲区解决
2,代码
//测试:生产者消费者模型-->利用缓冲区解决:管程法
public class PCTest {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container=container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container=container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了--》"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;//生产编号
public Chicken(int id) {
this.id=id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens=new Chicken[10];
//容量计数器
int count=0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if(count==chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count]=chicken;
count++;
//可以通知消费者消费了
this.notify();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if(count==0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken=chickens[count];
//吃完了,通知生产者生产
this.notify();
return chicken;
}
}
(6)解决方式二–信号灯法
1,信号灯法-利用标志位解决
2,代码
//测试生产者消费者问题2:信号灯法-标志位解决
public class PCTest2 {
public static void main(String[] args) {
TV tv=new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生产者-演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2==0){
this.tv.play("播放一半TV剧");
}else{
this.tv.play("播放一半广告");
}
}
}
}
//消费者-观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品-节目
class TV{
//演员表演,观众等待 T
//演员等待,观众表演 F
String voice;//表演的节目
boolean flag=true;
//表演
public synchronized void play(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:"+voice);
//通知观众观看
this.notify();//通知唤醒
this.voice=voice;
this.flag=!this.flag;
}
//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了:"+voice);
//通知演员表演
this.notify();
this.flag=!this.flag;
}
}
十三,线程池
(1)线程池
(2)线程池的使用
(3)Runnable
//测试线程池
public class PoolTest {
public static void main(String[] args) {
//1,创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service= Executors.newFixedThreadPool(10);
//执行Runnable接口的实现类
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2,关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
(4)Callable
//线程创建方式三:实现Callable接口 好处:可以定义返回值,可以抛出异常
public class CallableTest implements Callable<Boolean> {
private String url;//网络图片地址
private String name;//保存的文件名
public CallableTest(String url,String name){
this.url=url;
this.name=name;
}
@Override
public Boolean call() throws Exception {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了图片的文件名为:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableTest thread1Test1=new CallableTest("http://222.186.12.235:41001/Uploads/vod/2021-02-03/601a19c71e562.jpg","窥探1.jpg");
CallableTest thread1Test2=new CallableTest("http://pic.baike.soso.com/p/20110826/20110826220618-1504115653.jpg","窥探2.jpg");
CallableTest thread1Test3=new CallableTest("https://p0.itc.cn/images01/20210423/a454b56b139e433c81cf2f1aaad2ae7a.png","窥探3.jpg");
//创建执行服务
ExecutorService service= Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1=service.submit(thread1Test1);
Future<Boolean> r2=service.submit(thread1Test2);
Future<Boolean> r3=service.submit(thread1Test3);
//获取结果
boolean res1=r1.get();
boolean res2=r2.get();
boolean res3=r3.get();
//关闭服务
service.shutdownNow();
}
}
十四,回顾总结线程的创建
//回顾总结线程的创建
public class NewThread {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask=new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
Integer integer= null;
try {
integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1,继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("1,继承Thread类");
}
}
//2,实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("2,实现Runnable接口");
}
}
//3,实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("3,实现Callable接口");
return 100;
}
}