一.线程简介
1.核心概念
(1)线程就是独立的执行路径
(2)在程序运行时,即使没有自己创建线程,后台也会有多个线程,比如主线程,GC线程
(3)main()称之为主线程,为系统的入口,用于执行整个程序
(4)在一个进程中,如果开辟了多个线程,线程的运行是由调度器(cpu)安排调度的,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
(5)对同一份资源操作时mm会存在资源抢夺的问题,需要加入并发控制线程会带来额外的开销,如CPU调度时间,并发控制开销,每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
二.实现线程(三种方法)
1.继承Thread类(重要)
自定义线程类继承
Thread
类重写
run()
方法,编写线程执行体创建线程对象,调用
start()
方法启动线程public class ThreadTest extends Thread { @Override public void run() { //run方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我在看代码----" + i); } } public static void main(String[] args) { //创建一个线程对象 ThreadTest testThread = new ThreadTest(); //调用start()开启线程 testThread.start(); for (int i = 0; i < 200; i++) { System.out.println("我在学习多线程----" + i); } } }
总结:线程不一定立即执行,CPU安排调度
1.1练习 (下载图片)
这里通过maven仓库管理 对下面的案例进行测试
<!-- 导入多线程案例下载图片 io包--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency>
package com.chen.springbootholiday.Test;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习多线程案例
public class ThreadTest extends Thread{
private String url;
private String name;
//线程的执行体
@Override
public void run() {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载文件名为:"+name);
}
//有参构造
public ThreadTest(String url, String name) {
this.url = url;
this.name = name;
}
public static void main(String[] args) {
ThreadTest t1=new ThreadTest("https://img-home.csdnimg.cn/images/20201124032511.png", "1.png");
ThreadTest t2=new ThreadTest("https://img-home.csdnimg.cn/images/20201124032511.png", "2.png");
ThreadTest t3=new ThreadTest("https://img-home.csdnimg.cn/images/20201124032511.png", "3.png");
t1.start();
t2.start();
t3.start();
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("io执行出现异常");
}
}
}
}
2.实现Runnable接口(重要)
推荐使用Runnable对象,因为Java单继承的局限性
自定义线程类实现Runnable
接口
实现run()
方法,编写线程执行体
创建线程对象,调用start()
方法启动对象
package com.chen.springbootholiday.Test;
//创建线程通过实现Runnable接口
public class ThreadRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("我是线程方法执行体"+i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 200; i++) {
System.out.println("我是主线程"+i);
}
ThreadRunnable threadRunnable=new ThreadRunnable();;
//创建线程
// Thread thread=new Thread(threadRunnable);
// thread.start();
//创建线程对象 进行代理
new Thread(threadRunnable).start();
}
}
2.1Runnable案例
package com.chen.springbootholiday.Test;
//抢票案例
public class RunnableTest implements Runnable {
private Integer ticket=10;
@Override
public void run() {
while (true){
if(ticket<=0){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢到第"+ticket-- +"票");
}
}
public static void main(String[] args) {
RunnableTest rt=new RunnableTest();
new Thread(rt,"小王").start();
new Thread(rt,"小陈").start();
new Thread(rt,"校长").start();
}
}
3.实现Callable接口(了解)
实现Callable接口,需要返回值类型
重写call方法,需要抛出异常
创建目标对象
创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
提交执行:Future result1 = ser.submit(11);
获取结果:boolean r1 = result1.get()
关闭服务:ser.shutdownNow();
好处
可以定义返回值
可以抛出异常
package com.chen.springbootholiday.Test;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class ThreadCallable implements Callable<Boolean> {
private String url;
private String name;
//线程的执行体
@Override
public Boolean call() {
ThreadCallable.WebDownloader webDownloader=new ThreadCallable.WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载文件名为:"+name);
return true;
}
//有参构造
public ThreadCallable(String url, String name) {
this.url = url;
this.name = name;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadCallable t1=new ThreadCallable("https://img-home.csdnimg.cn/images/20201124032511.png", "1.png");
ThreadCallable t2=new ThreadCallable("https://img-home.csdnimg.cn/images/20201124032511.png", "2.png");
ThreadCallable t3=new ThreadCallable("https://img-home.csdnimg.cn/images/20201124032511.png", "3.png");
//创建执行服务
//将线程放进去
ExecutorService es= Executors.newFixedThreadPool(3);
//执行提交
Future<Boolean> f1 = es.submit(t1);
Future<Boolean> f2 = es.submit(t2);
Future<Boolean> f3 = es.submit(t3);
//获取结果
Boolean b1 = f1.get();
Boolean b2 = f2.get();
Boolean b3 = f3.get();
//关闭结果
es.shutdown();
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("io执行出现异常");
}
}
}
}
4.Thread和Runnable对比
继承Thred类:
子类继承Thread类具备多线程能力
启动线程:子类对象.start()
不建议使用:避免OOP单继承局限性
实现Runnable接口实现接口Runnable具有多线程能力
启动线程:传入目标对象+Thread对象.start()
推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
5.静态代理
总结
真实对象和代理对象都要实现一个接口
代理对象要代理真实角色好处
代理对象可以做很多真实对象做不了的事情
真实对象专注做自己的事
5.1结婚案例
package com.chen.springbootholiday.Test;
public class StaticProxy {
public static void main(String[] args) {
//进行调用
WeddingCompany weddingCompany = new WeddingCompany(new Your());
weddingCompany.Happy();
}
//定义共同的接口
interface Marry{
void Happy();
}
//真实角色 进行结婚
static class Your implements Marry{
@Override
public void Happy() {
System.out.println("要结婚了,开心");
}
}
//婚庆公司 代理你准备布置工作
static class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void Happy() {
before();
System.out.println("进行现场布置");
this.target.Happy();
after();
}
private void before() {
System.out.println("结婚前布置现场");
}
private void after() {
System.out.println("结婚后,收尾款");
}
}
}
6.lamda介绍
6.1函数式接口的定义:
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口.
lamda推导
package com.chen.springbootholiday.Test2;
import java.util.logging.Level;
public class Lamda {
public static void main(String[] args) {
//进行方法调用
Like like=new Like();
like.lamda();
//内部类调用
Like1 like1=new Like1();
like1.lamda();
//3.局部内部类
class Like2 implements Ilike{
@Override
public void lamda() {
System.out.println("Lamda is good 局部内部类");
}
}
//局部内部类调用
Like2 like2=new Like2();
like2.lamda();
//4.匿名内部类 没有类的名称 实现接口或者借助父类
Like like3=new Like(){
@Override
public void lamda() {
System.out.println("lamda is good 匿名内部类");
}
};
like3.lamda();
//lamda表达式
Ilike ilike=()->{
System.out.println("lamda最终版");
};
ilike.lamda();
}
//2.静态内部类
static class Like1 implements Ilike{
@Override
public void lamda() {
System.out.println("Lamda is good 静态内部类");
}
}
}
//定义接口
interface Ilike{
void lamda();
}
//1.实现一个接口
class Like implements Ilike{
@Override
public void lamda() {
System.out.println("Lamda is good");
}
}
练习
package com.chen.springbootholiday.Test2;
public class LamdaTest {
public static void main(String[] args) {
Ilove ilove=(int a)->{
System.out.println("I love you"+a);
};
ilove.love(520);
}
}
//定义接口
interface Ilove{
void love(int a);
}
三.线程状态
1.线程五大状态
2.线程停止
package com.chen.springbootholiday.Test2;
//进行线程停止
//用一个标识符的布尔值 进行判读
public class TestStop implements Runnable{
private boolean flag=true;
@Override
public void run() {
int i=0;
while (flag){
System.out.println("线程 is running"+i++);
}
}
//定义方法 用于线程停止
public void testStop(){
this.flag=false;
}
//主线程 用于线程方法调用
public static void main(String[] args) {
TestStop ts=new TestStop();
new Thread(ts).start();
for (int i = 0; i < 500; i++) {
System.out.println("当前线程进行的数字为"+i);
if(i==400){
ts.testStop();
System.out.println("线程停止");
}
}
}
}
3.线程休眠
package com.chen.springbootholiday.Test2;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
//模拟倒计时
public class TestSleep {
public void tenDown() throws InterruptedException {
int num=10;
while (true){
Thread.sleep(100);
System.out.println("num为"+num--);
if(num<=0){
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
TestSleep ts = new TestSleep();
ts.tenDown();
//获取系统当前时间
Date startTime=new Date(System.currentTimeMillis());
while (true){
Thread.sleep(1000);
System.out.println("当前时间为"+ new SimpleDateFormat("HH:mm:ss").format(startTime));
//更新时间
startTime=new Date(System.currentTimeMillis());
}
}
}
4.线程礼让
package com.chen.springbootholiday.Test2;
//测试线程礼让
public class TestYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
public static void main(String[] args) {
TestYield ty=new TestYield();
new Thread(ty,"a").start();
new Thread(ty,"b").start();
}
}
5.线程插队
join合并线程 等此线程执行完后在执行其他线程 类似于插队
package com.chen.springbootholiday.Test2;
//线程插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是vip"+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin=new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 300; i++) {
if(i==100){
thread.join();
}
System.out.println("主线程main"+i);
}
}
}
6.线程状态观察
package com.chen.springbootholiday.Test2;
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ok");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//new
//调用线程
thread.start();
state=thread.getState();
System.out.println(state);
//判断是否停止
while (state!=Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}
7.线程优先级
package com.chen.springbootholiday.Test3;
//线程优先级
public class TestPriorty {
public static void main(String[] args) {
//主线程的优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriorty myPriorty = new MyPriorty();
Thread thread1 = new Thread(myPriorty);
Thread thread2 = new Thread(myPriorty);
Thread thread3 = new Thread(myPriorty);
Thread thread4 = new Thread(myPriorty);
//设置优先级 在启动
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY);
thread4.start();
}
}
class MyPriorty implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
8.守护线程
package com.chen.springbootholiday.Test3;
//守护线程
public class TestDaemon {
public static void main(String[] args) {
God god=new God();
Thread thread=new Thread(god);
thread.setDaemon(true);//设置为守护线程 默认都是false 为用户线程
thread.start();
You you=new You();
new Thread(you).start();
}
}
//创建用户线程
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 3650; i++) {
System.out.println("十年都在开心的活着"+i);
}
System.out.println("GoodBye World");
}
}
//创建守护线程
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑着你");
}
}
}
四.线程同步
1.并发
同一个对象被多个线程同时操作
2.三大不安全线程案例
2.1买票
package com.chen.springbootholiday.Test3;
public class SynTicket {
public static void main(String[] args) {
Ticket t=new Ticket();
new Thread(t,"小明").start();
new Thread(t,"小王").start();
new Thread(t,"小陈").start();
}
}
//创建票类
class Ticket implements Runnable{
//定义票数
private int ticket=10;
//进行线程停止
boolean flag=true;
@Override
public void run() {
//通过标志进行线程停止
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//提供购票方法
private void buy() throws InterruptedException {
//判断是否有票
if(ticket<=0){
flag=false;
return;
}
//进行线程睡眠
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"拿到票"+ticket--);
}
}
2.2两人同时取钱
package com.chen.springbootholiday.Test3;
import lombok.SneakyThrows;
//模拟取钱
public class SynBank {
public static void main(String[] args) {
Account account=new Account(100,"基金");
Drawing you=new Drawing(account,50,"自己");
Drawing girlfriend =new Drawing(account,100,"女朋友");
you.start();
girlfriend.start();
}
}
//卡号
class Account{
int money;
String cardName;
public Account(int money, String cardName) {
this.money = money;
this.cardName = cardName;
}
}
class Drawing extends Thread{
//账户
Account account;
//取的余额
int drawingMoney;
//剩余的钱
int newMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account=account;
this.drawingMoney=drawingMoney;
}
@Override
public void run(){
if(account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"余额不足");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额
account.money=account.money-drawingMoney;
//手里余额
newMoney=newMoney+drawingMoney;
System.out.println(account.cardName+"余额为"+account.money);
System.out.println(Thread.currentThread().getName()+"手里的钱"+newMoney);
}
}
2.3不安全的集合
package com.chen.springbootholiday.Test3;
import java.util.ArrayList;
import java.util.List;
public class SynConnection {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}
3.同步方法和同步代码块
3.1同步方法
同步方法锁的是 this
package com.chen.springbootholiday.Test3;
public class SynTicket {
public static void main(String[] args) {
Ticket t=new Ticket();
new Thread(t,"小明").start();
new Thread(t,"小王").start();
new Thread(t,"小陈").start();
}
}
//创建票类
class Ticket implements Runnable{
//定义票数
private int ticket=10;
//进行线程停止
boolean flag=true;
@Override
public void run() {
//通过标志进行线程停止
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//提供购票方法
//synchronized同步方法 锁的是this 指的就是Ticket 对象本身
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticket<=0){
flag=false;
return;
}
//进行线程睡眠
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"拿到票"+ticket--);
}
}
3.2同步代码块
锁的是需要增删改的对象
package com.chen.springbootholiday.Test3;
import lombok.SneakyThrows;
//模拟取钱
public class SynBank {
public static void main(String[] args) {
Account account=new Account(1000,"基金");
Drawing you=new Drawing(account,50,"自己");
Drawing girlfriend =new Drawing(account,100,"女朋友");
you.start();
girlfriend.start();
}
}
//卡号
class Account{
int money;
String cardName;
public Account(int money, String cardName) {
this.money = money;
this.cardName = cardName;
}
}
class Drawing extends Thread{
//账户
Account account;
//取的余额
int drawingMoney;
//剩余的钱
int newMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account=account;
this.drawingMoney=drawingMoney;
}
@Override
public void run(){
//加同步代码块 可以锁任何对象
synchronized (account){
if(account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"余额不足");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额
account.money=account.money-drawingMoney;
//手里余额
newMoney=newMoney+drawingMoney;
System.out.println(account.cardName+"余额为"+account.money);
System.out.println(Thread.currentThread().getName()+"手里的钱"+newMoney);
}
}
}
package com.chen.springbootholiday.Test3;
import java.util.ArrayList;
import java.util.List;
public class SynConnection {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
4. 拓展JUC安全集合类型
package com.chen.springbootholiday.Test4;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC并发
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
5.死锁
某个同步块拥有两个以上的对象的锁,就会发生死锁问题
5.1案例
package com.chen.springbootholiday.Test4;
public class TestLock {
public static void main(String[] args) {
Makeup m1=new Makeup(0,"灰姑娘");
Makeup m2=new Makeup(1,"白雪公主");
new Thread(m1).start();
new Thread(m2).start();
}
}
//定义镜子
class Mirror{}
//定义口红
class Lipstick{}
//定义资源
class Makeup implements Runnable{
//通过static修饰将资源设置为一份
static Lipstick lipstick=new Lipstick();
static Mirror mirror=new Mirror();
//设置选择数量(用于后面的判断)和名字
int choice;
String girlName;
public Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//进行方法的调用
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public 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(2000);
synchronized (lipstick){
System.out.println(this.girlName+"获得镜子的锁");
}
}
}
}
}
5.2解决
public 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(2000);
synchronized (lipstick){
System.out.println(this.girlName+"获得镜子的锁");
}
}
}
5.3避免死锁
6.Lock锁
package com.chen.springbootholiday.Test4;
import java.util.concurrent.locks.ReentrantLock;
//测试Lock
public class Test {
public static void main(String[] args) {
Ticket ticket=new Ticket();
new Thread(ticket,"小王").start();
new Thread(ticket,"小明").start();
new Thread(ticket,"小红").start();
}
}
class Ticket implements Runnable{
int ticketNumber=10;
//定义Lock锁
private final ReentrantLock reentrantLock=new ReentrantLock();
@Override
public void run() {
while (true){
//加锁
try {
reentrantLock.lock();
if(ticketNumber<=0){
break;
}else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ticketNumber--);
}
}finally {
reentrantLock.unlock();
}
}
}
}
7.Synchronized和Lock锁区别
五.线程通信
5.1生产者消费者 管程法
package com.chen.springbootholiday.Test4;
//线程通信 管程法
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer=new SynContainer();
new Producer(synContainer).start();
new Consumer(synContainer).start();
}
}
//定义生产者
class Producer extends Thread{
SynContainer synContainer;
public Producer (SynContainer synContainer){
this.synContainer=synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synContainer.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//定义消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer (SynContainer synContainer){
this.synContainer=synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了"+synContainer.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) {
//容器满了就等待消费者进行消费
while (count==chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//容器未满 继续生产
chickens[count]=chicken;
count++;
this.notifyAll();
}
//消费者进行消费
public synchronized Chicken pop(){
while (count<=0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//可以消费
count--;
Chicken chicken=chickens[count];
this.notifyAll();
return chicken;
}
}
5.2生产者消费者 标志法
package com.chen.springbootholiday.Test4;
//线程通信 标志位 模拟电视表演节目观看
public class TestFlag {
public static void main(String[] args) {
TV tv=new TV();
new Actor(tv).start();
new Audience(tv).start();
}
}
//定义演员
class Actor extends Thread{
TV tv;
public Actor(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2==0){
tv.show("表演了马戏团");
}else {
tv.show("表演抖音");
}
}
}
}
//定义观众
class Audience extends Thread{
TV tv;
public Audience(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//定义电视
class TV{
//定义标志位
Boolean flag=true; //true 演员表演 false 观众观看
//表演节目
String voice;
//表演
public synchronized void show(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了"+voice);
//通知观众观看
this.notifyAll();
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.notifyAll();
this.flag=!this.flag;
}
}
六.线程池
package com.chen.springbootholiday.Test4;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
MyThread myThread=new MyThread();
//创建线程池 大小
ExecutorService executorService= Executors.newFixedThreadPool(10);
//执行
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
//关闭连接
executorService.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}