多线程
1、概述进程线程多线程
2、线程创建
2-1Thread
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
- 线程不一定立即执行,CPU安排调度
public class DemoThread01 extends Thread{
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:注意*,线程开启不一定立即执行,由CPU调度
public void run(){
for (int i = 0; i < 200 ; i++) {
System.out.println("今天起来拥抱太阳"+i);
}
}
public static void main(String[] args) {
//main线程是主线程
//创建线程对象
DemoThread01 demoThread01 = new DemoThread01();
//直接调用run()方法,肯定是先执行run()方法
demoThread01.run();
//如果调用start()方法,会随机执行main()与run()
demoThread01.start();
for (int i = 0; i < 2000; i++) {
System.out.println("今天心情美美哒!"+i);
}
}
}
//练习Thread,实现多线程同步下载图片
//前提需要导入commons-io-2.11.0.jar包
public class DemoThread02 extends Thread {
private String url; //网络图片地址
private String name; //保存的文件 名
public DemoThread02(String url, String name) {
this.url = url;
this.name = name;
}
public void run(){
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载文件名为:"+name);
}
public static void main(String[] args) {
DemoThread02 t1 = new DemoThread02("https://img-pre.ivsky.com/img/tupian/pre/202103/24/sunyunzhu_xiushen_duanqun-003.jpg","1.jpg");
DemoThread02 t2 = new DemoThread02("https://img-pre.ivsky.com/img/tupian/pre/202103/24/sunyunzhu_xiushen_duanqun-003.jpg","2.jpg");
DemoThread02 t3 = new DemoThread02("https://img-pre.ivsky.com/img/tupian/pre/202103/24/sunyunzhu_xiushen_duanqun-003.jpg","3.jpg");
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 ioException) {
ioException.printStackTrace();
System.out.println("IO异常,diwnloader方法出现问题");
}
}
}
}
2-2实现Runnable
定义MyRunnable
类实现Runnable接口- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
public class DemoThread03 implements Runnable{
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable实现类,调用start方法
public void run(){
for (int i = 0; i < 200 ; i++) {
System.out.println("今天起来拥抱太阳"+i);
}
}
public static void main(String[] args) {
//创建Runnable接口的实现类对象
DemoThread03 demoThread03 = new DemoThread03();
//创建线程对象,通过线程对象来开启我们线程,代理
new Thread(demoThread03).start();
for (int i = 0; i < 2000; i++) {
System.out.println("今天心情美美哒!"+i);
}
}
}
小结
-
继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
-
实现Runnable接口
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多线程使用
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题,多线程操作同一个资源的情况下,线程不安全,数据缭乱,并发问题
public class DemoThread04 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true){
if(ticketNums<=1){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
DemoThread04 ticket = new DemoThread04();
new Thread(ticket,"李茂").start();
new Thread(ticket,"大涛").start();
new Thread(ticket,"齐哥").start();
}
}
package Thread;
//模拟龟兔赛跑
public class DemoThread05 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(5);
} 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;
}{
if(steps>=100){
winner = Thread.currentThread().getName();
System.out.println("winner is "+ winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
DemoThread05 race = new DemoThread05();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
2-3实现Callable接口
-
实现callable接口,需要返回值类型
-
重写call方法,需要抛出异常
-
创建Ian目标对象
-
创建执行服务:
ExecutorService ser = Executor.newFixedThreadPool(1)
; -
提交执行:
Future<Boolean> result1 =ser.submit(t1);
-
获取结果:
boolean r1 = result1.get()
-
关闭服务:
Ser.shutdownNow();
/**
* 创建线程三:实现callable接口
*callable的好处
*1.可以定义返回值
*2.可以抛出异常
*/
public class DemoThread0 implements Callable<Boolean> {
private String url; //网络图片地址
private String name; //保存的文件 名
public DemoThread0(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载文件名为:"+name);
return true;
}
public static void main(String[] args) {
DemoThread0 t1 = new DemoThread0("https://img-pre.ivsky.com/img/tupian/pre/202103/24/sunyunzhu_xiushen_duanqun-003.jpg","4.jpg");
DemoThread0 t2 = new DemoThread0("https://img-pre.ivsky.com/img/tupian/pre/202103/24/sunyunzhu_xiushen_duanqun-003.jpg","5.jpg");
DemoThread0 t3 = new DemoThread0("https://img-pre.ivsky.com/img/tupian/pre/202103/24/sunyunzhu_xiushen_duanqun-003.jpg","6.jpg");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<?> s1 = ser.submit(t1);
Future<?> s2 = ser.submit(t2);
Future<?> s3= ser.submit(t3);
// 获取结果
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
// 关闭服务
ser.shutdownNow();
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException ioException) {
ioException.printStackTrace();
System.out.println("IO异常,diwnloader方法出现问题");
}
}
}
}
3、静态代理模式
/**
* 静态代理模式总结:
* 真是对象和代理对象都要实现同一个接口
* 代理对象要代理真实角色
*/
//好处:
//代理对象可以做很多真是对象做不了的事情
//真是对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
new Thread(()-> System.out.println("我爱你")).start();
new WeddingCompany(new You() ).HappyMarry();
/* WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.HappyMarry();*/
}
}
//创建共同目标:结婚
interface Marry{
//人家四大喜事
/*
久旱逢甘露,他乡遇故知。
洞房花烛夜,金榜题名时。
*/
void HappyMarry();
}
//真是角色
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("大涛等有钱要结婚了,超级开心!!!");
}
}
//代理角色,婚庆公司,-需要接受结婚对象
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 after() {
System.out.println("结婚之后收尾款");
}
private void before() {
System.out.println("结婚之前布置现场");
}
}
4、Lamda表达式
- 避免匿名内部类定义过多
- 其实质属于函数式编程的概念
- 理解Functional Interface(函数式接口)是学习Java8 lambda表达式的关键所在。
- 函数式接口的定义:
- 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。
- 对于函数式接口,我们可以通过lambda表达式来创建该接口的对象。
package Lamda;
public class DemoLamba {
//3.静态内部类
static class Like2 implements ILike {
@Override
public void lamba() {
System.out.println("i like lamba2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lamba();
like = new Like2();
like.lamba();
//4.局部内部类
class Like3 implements ILike {
@Override
public void lamba() {
System.out.println("i like lamba3");
}
}
like = new Like3();
like.lamba();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lamba() {
System.out.println("i like lamba4");
}
};
like.lamba();
//6.用lamda简化
like = ()->{
System.out.println("i like lamba5");
};
like.lamba();
}
}
//1.定义接口
interface ILike{
void lamba();
}
//2.实现类
class Like implements ILike{
@Override
public void lamba() {
System.out.println("i like lamba1");
}
}
package Lamda;
public class Love {
public static void main(String[] args) {
Ilove ilove = null;
//简化括号
ilove = a -> {
System.out.println("爱你呦"+"+"+a);
};
ilove.love(1);
}
//总结
//lamda表达式只能有一行代码的请况下才能简化成为一行,如果有多行,那么就用代码块包裹。
//前提是接口为函数式接口
//多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
interface Ilove{
void love(int a);
}
}
5、线程状态
-
不推荐使用JDK提供的stop()、destory()方法。【已废弃】
-
推荐线程自己停止下来
-
建议使用一个标识位进行终止变量。当flag=false,则终止线程运行。
5-1线程停止_Stop
//测试stop
//1.建议线程正常停止--->利用次数,不建议死循环
//2.建议使用标志位--->设置一个标志位
//3.不要使用stop或者destory等过时或JDK不建议使用方法
public class DemoStop 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) {
DemoStop demoStop = new DemoStop();
new Thread(demoStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
//调用stop方法切换标识位,让线程停止
demoStop.stop();
System.out.println("线程该停止了");
}
}
}
}
5-2线程休眠_Sleep
- sleep(时间)指定当前线程紫色的毫秒数;
- sleep存在异常InterruptedException;
- sleep时间达到后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等;
- 每一个对象都有一个锁,sleep不会释放锁;
//模拟倒计时
public class DemoSleep2 {
public static void main(String[] args) {
//打印系统当前时间
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*try {
tenDown();
}catch (InterruptedException e){
e.printStackTrace();
}*/
}
public static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
5-3线程礼让_Yield
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重新调度,礼让不一定成功!看cpu心情
//测试礼让线程
//礼让不成功,看cpu心情
public class DemoYield {
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()+"线程停止执行");
}
}
5-4线程强制执行_Join
- Join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞
- 可以想象成插队
//测试join方法
public class DemoJoin 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 {
//启动我们的线程
DemoJoin demoJoin = new DemoJoin();
Thread thread = new Thread(demoJoin);
thread.start();
//主线程
for (int i = 0; i < 500 ; i++) {
if(i == 200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
5-5线程状态
public class DemoStat {
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();
}
}
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//NEW
//观察启动后
thread.start();//启动线程
state = thread.getState();//Run
System.out.println(state);
while (state != Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
5-6线程优先级
public class DemoPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
//先设置优先级,在启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(Thread.MAX_PRIORITY);
t3.start();
t4.setPriority(8);
t4.start();
t5.setPriority(9);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
5-7守护线程
public class DemoMain {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true);//默认是false表示是用户线程,正常的线程都是用户线程
thread.start();//上帝守护线程启动
new Thread(you).start(); //用户线程启动
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑着你");
}
}
}
//in
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("-=====good=====-");
}
}
6、线程同步机制
线程同步
- 多个线程操作同一个资源
并发
- 同一个对象被多个线程同时操作
队列和锁
package syn;
//不安全买票
//线程不安全有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"苦逼的我").start();
new Thread(station,"牛逼的你们").start();
new Thread(station,"可恶的黄牛党").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (true){
buy();
}
}
private void buy(){
//判断是否买票
if(ticketNums<=0){
flag = false;
return;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package syn;
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;//账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
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;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//Thread.currentThread().getName() = this.getName()
System.out.println(this.getName()+"手里的钱"+ nowMoney);
}
}
package syn;
import java.util.ArrayList;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10000 ; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
同步方法
同步块
package syn;
//不安全买票
//线程不安全有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"苦逼的我").start();
new Thread(station,"牛逼的你们").start();
new Thread(station,"可恶的黄牛党").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (true){
buy();
}
}
private synchronized void buy(){
//判断是否买票
if(ticketNums<=0){
flag = false;
return;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package syn;
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;//账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
//synchronized默认锁this
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;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//Thread.currentThread().getName() = this.getName()
System.out.println(this.getName()+"手里的钱"+ nowMoney);
}
}
}
package syn;
import java.util.ArrayList;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10000 ; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
package syn;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class DemoJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10000 ; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
package syn;
//死锁:多个线程相互抱着对方需要的资源,然后行成坚持
public class DemoLock {
public static void main(String[] args) {
Makeup m1 = new Makeup(0,"灰姑凉");
Makeup m2 = new Makeup(1,"白雪公主");
m1.start();
m2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror {
}
class Makeup extends Thread {
//需要的资源只能有一,用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;
}
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(2000);
}
synchronized (lipstick){ //一秒钟后获得镜子的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
Lock锁
public class DemoLock {
public static void main(String[] args) {
DemoLock2 demoLock2 = new DemoLock2();
new Thread(demoLock2).start();
new Thread(demoLock2).start();
new Thread(demoLock2).start();
}
}
class DemoLock2 implements Runnable{
int tickettNums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try{
lock.lock();//枷锁
if(tickettNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tickettNums--);
}else{
break;
}
}
finally {
//解锁
lock.unlock();
}
}
}
}
7、生产者消费者问题
管程法
package gaoji;
import sun.font.FontRunIterator;
//测试:生产者消费者模型-->利用那个缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class DemoPC {
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;
}
//生产
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;
}
//消费
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.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if(count == 0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法
package gaoji;
//测试生产者消费者问题2:信号灯法,标志位解决
public class DemoPC2 {
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;
}
public void run(){
for (int i = 0; i < 4; i++) {
if(i%2 == 0){
this.tv.play("快乐大本营播放中");
}else{
this.tv.play("抖音,记录美好生活");
}
}
}
}
//消费者-->观众
class Watcher extends Thread{
TV tv;
public Watcher( TV tv) {
this.tv = tv;
}
public void run(){
for (int i = 0; i < 4; 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.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 gaoji;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DemoPoll {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭连接
service.shutdownNow();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}