标签:alt adl 缺陷 内部类 pool produce object 另一个 队列
程序是指令与数据的有序集合,其本身没有任何运行的含义,是一个静态的概念
进程(Process)则是执行程序的一次执行过程,是一个动态的概念!是系统资源分配的单位
通常情况下,一个进程可以包含若干个线程(Thread),且一个进程中至少包含一个线程,线程是cpu调度和执行的单位
注意:大多数多线程是模拟实现的,真正的多线程是有多个cpu的。模拟实现的线程在一个cpu的情况下可能存在执行的错句
package cn.imut;
public class ThreadTest extends Thread{
@Override
public void run() {
//run线程
for(int i = 0; i < 20; i++) {
System.out.println("run写代码~~~" + i);
}
}
public static void main(String[] args) {
//创建一个线程对象
ThreadTest threadTest = new ThreadTest();
//开启线程
threadTest.start();
//main线程
for(int i = 0; i < 20; i++) {
System.out.println("main写代码~~~" + i);
}
}
}
总结:线程开启不一定立即执行,由cpu调度执行
eg:多线程同步下载图片
package cn.imut;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
//多线程同步下载图片
public class ThreadTest2 extends Thread{
private String url; //图片地址
private String name; //图片文件名
public ThreadTest2(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:" + name);
}
public static void main(String[] args) {
ThreadTest2 t1 = new ThreadTest2("https://images.cnblogs.com/cnblogs_com/yfyyy/1650644/o_200219124004IMG_20191121_154347%20(2).jpg", "1.jpg");
ThreadTest2 t2 = new ThreadTest2("https://images.cnblogs.com/cnblogs_com/yfyyy/1650644/o_200219124004IMG_20191121_154347%20(2).jpg", "2.jpg");
ThreadTest2 t3 = new ThreadTest2("https://images.cnblogs.com/cnblogs_com/yfyyy/1650644/o_200219124004IMG_20191121_154347%20(2).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 e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
package cn.imut;
public class ThreadTest3 implements Runnable{
@Override
public void run() {
//run线程
for(int i = 0; i < 2000; i++) {
System.out.println("run写代码~~~" + i);
}
}
public static void main(String[] args) {
//创建Runnable接口的实现对象
ThreadTest3 threadTest3 = new ThreadTest3();
//创建线程对象,通过线程对象开启线程
// Thread thread = new Thread();
// thread.start();
new Thread(threadTest3).start();
//main线程
for(int i = 0; i < 2000; i++) {
System.out.println("main写代码~~~" + i);
}
}
}
总结
package cn.imut;
//多个线程同时操作同一个对象
public class ThreadTest4 implements Runnable{
private int ticketNums = 10; //票数
@Override
public void run() {
while (ticketNums > 0) {
//Thread.currentThread().getName() 得到当前线程名字
System.out.println(Thread.currentThread().getName() + "-->拿到了" + ticketNums-- + "票");
}
}
public static void main(String[] args) {
ThreadTest4 threadTest4 = new ThreadTest4();
new Thread(threadTest4,"zl").start();
new Thread(threadTest4,"jssb").start();
new Thread(threadTest4,"2bsb").start();
}
}
存在并发问题!
eg:龟兔赛跑,模拟兔子睡觉
package cn.imut;
//模拟龟兔赛跑
public class Race 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(1);
} 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) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
eg:下载图片
package cn.imut;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class CallableTest implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:" + name);
return true;
}
private String url; //图片地址
private String name; //图片文件名
public CallableTest (String url, String name) {
this.url = url;
this.name = name;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableTest t1 = new CallableTest("https://images.cnblogs.com/cnblogs_com/yfyyy/1650644/o_200219124004IMG_20191121_154347%20(2).jpg", "1.jpg");
CallableTest t2 = new CallableTest("https://images.cnblogs.com/cnblogs_com/yfyyy/1650644/o_200219124004IMG_20191121_154347%20(2).jpg", "2.jpg");
CallableTest t3 = new CallableTest("https://images.cnblogs.com/cnblogs_com/yfyyy/1650644/o_200219124004IMG_20191121_154347%20(2).jpg", "3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(1);
//提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
//获取结果
boolean rs1 = result1.get();
boolean rs2 = result2.get();
boolean rs3 = result3.get();
//关闭服务
ser.shutdownNow();
}
}
//下载器
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异常");
}
}
}
结婚接口
package cn.imut2;
public interface Marry {
//结婚
void HappyMarry();
}
代理对象(婚庆公司)
package cn.imut2;
//代理角色
public 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("布置婚礼现场");
}
}
真实角色(要结婚的人)
package cn.imut2;
//真是角色
public class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("我要结婚了~");
}
}
结婚
package cn.imut2;
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany company = new WeddingCompany(new You());
company.HappyMarry();
}
}
静态代理模式总结
λ是希腊字母表中排序第十一位的字母,英语名称为Lambda,可以避免匿名内部类定义过多,其实质属于函数式编程的概念
(paramx) -> expression[表达式]
(params) -> statement[语句]
(params) -> {statements}
函数式接口的定义
package cn.imut3;
public class LamdbaTest {
public static void main(String[] args) {
ILike like = new Like();
like.lamdba();
like = new Like2();
like.lamdba();
//3.局部内部类
class Like3 implements ILike{
@Override
public void lamdba() {
System.out.println("I Like Lamdba3");
}
}
like = new Like3();
like.lamdba();
//4.匿名内部类
like = new ILike() {
@Override
public void lamdba() {
System.out.println("I Like Lamdba4");
}
};
like.lamdba();
//5.再简化 Lomdba
like = () -> {
System.out.println("I like Lomdba5");
};
like.lamdba();
}
//2.静态内部类
static class Like2 implements ILike{
@Override
public void lamdba() {
System.out.println("I Like Lamdba2");
}
}
}
推进过程
love = a-> System.out.println("i love you -->" + a)
总结:lambda表达式只能由一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹,前提是接口为函数式接口
new
Thread t = new Thread() 线程对象一旦创建就进入到新生状态
就绪状态
调用start()方法,线程立即进入就绪状态,但不意味着立即调度执行
阻塞状态
当调用sleep,wait或同步锁定时,线程进入阻塞状态,即代码不往下执行,阻塞事件解除后,重新进入就绪状态,等待cpu调度执行
运行状态
线程开始执行代码块
dead
线程中断或者结束,一旦进入死亡状态,就不能再次启动
package cn.imut4;
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 < 1000; i++) {
System.out.println("main" + i);
if(i == 900) {
//调用stop方法切换标志位,让线程停止
stopTest.stop();
System.out.println("线程停止!");
}
}
}
}
模拟倒计时
package cn.imut4;
public class SleepTest2 {
public static void main(String[] args) {
tenDown();
}
public static void tenDown() {
int nums = 10;
while (true) {
try {
Thread.sleep(1000); //1000毫秒
System.out.println(nums--);
if(nums <= 0) {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
买票模拟延迟
package cn.imut4;
import cn.imut.ThreadTest4;
//模拟网页延迟:方法问题的发生性
public class SleepTest implements Runnable{
private int ticketNums = 10; //票数
@Override
public void run() {
while (ticketNums > 0) {
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Thread.currentThread().getName() 得到当前线程名字
System.out.println(Thread.currentThread().getName() + "-->拿到了" + ticketNums-- + "票");
}
}
public static void main(String[] args) {
ThreadTest4 threadTest4 = new ThreadTest4();
new Thread(threadTest4,"zl").start();
new Thread(threadTest4,"jssb").start();
new Thread(threadTest4,"2bsb").start();
}
}
package cn.imut4;
//礼让线程(不一定成功)
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()+ "线程停止执行");
}
}
package cn.imut4;
public class JoinTest implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("插队了" + 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 < 1000; i++) {
if(i == 200) {
thread.join();
}
System.out.println("main" + i);
}
}
}
一个线程可以在给定时间点处于一个状态。这些状态是不反应任何操作系统线程状态的虚拟机状态
package cn.imut4;
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();
System.out.println(thread.getState());
while (thread.getState() != Thread.State.TERMINATED){ //只要线程不终止,就一直输出状态
Thread.sleep(100);
System.out.println(thread.getState());
}
}
}
package cn.imut5;
//测试线程的优先级
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);
Thread thread5 = new Thread(myPriority);
Thread thread6 = new Thread(myPriority);
//先设置优先级
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY); //10
thread4.start();
thread5.setPriority(1);
thread5.start();
thread6.setPriority(2);
thread6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
}
}
优先级低只意味着获取调度的概率低!
package cn.imut5;
//守护线程
public class DaemonTest {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread();
thread.setDaemon(true); //默认是用户线程
thread.start(); //大帝线程启动
new Thread(you).start(); //弱鸡启动
}
}
//大帝
class God implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("仙路尽头谁为峰,一见无始道成空");
}
}
}
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("开始修仙升级");
}
System.out.println("============成为大帝===========");
}
}
多个线程操作同一个资源
并发:同一个对象被多个线程同时操作
买票、取钱等...
处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时就需要线程同步。线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
形成条件:队列 + 锁
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入 锁机制 synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可
排队买票(线程不安全,有负数)
package cn.imut6;
import java.time.temporal.Temporal;
import java.util.function.Predicate;
//不安全的买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"1号").start();
new Thread(buyTicket,"2号").start();
new Thread(buyTicket,"3号").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--);
}
}
取钱(余额出现负数)
package cn.imut6;
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "建设银行信用卡");
Drawing you = new Drawing(account, 50, "你");
Drawing dog = new Drawing(account, 100, "二狗");
you.start();
dog.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;
}
//取钱
@Override
public void run() {
//判断有没有钱
if(account.money - drawingMoney < 0) {
System.out.println("余额不足,无法取出");
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);
//
System.out.println(this.getName()+Thread.currentThread().getName() + "手里的钱:" + nowMoney);
}
}
List不安全
package cn.imut6;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
new Thread(() -> {
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
缺陷:将一个方法声明为synchronized 会影响效率
package cn.imut6;
import java.time.temporal.Temporal;
import java.util.function.Predicate;
//不安全的买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"1号").start();
new Thread(buyTicket,"2号").start();
new Thread(buyTicket,"3号").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();
}
}
}
//同步方法,加锁,锁定是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums <= 0) {
flag = false;
return;
}
//延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "买到" + ticketNums--);
}
}
//取钱
@Override
public void run() {
synchronized (account){
//判断有没有钱
if(account.money - drawingMoney < 0) {
System.out.println("余额不足,无法取出");
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);
//
System.out.println(this.getName()+Thread.currentThread().getName() + "手里的钱:" + nowMoney);
}
}
package cn.imut6;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 100000; 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 cn.imut6;
import java.util.concurrent.CopyOnWriteArrayList;
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(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
多个线程各自占有一些资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一同步代码块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”问题。
package cn.imut7;
import cn.imut2.Marry;
//死锁:多个线程互相等待
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "1号女孩");
Makeup makeup1 = new Makeup(1, "2号女孩");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick {
}
//镜子
class Mirror {
}
class Makeup extends Thread {
static final Lipstick lipstick = new Lipstick();
static final 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){ //1s后获得镜子
System.out.println(this.girlName + "获得镜子的锁");
}
}
}else {
synchronized (mirror) { //获得口红的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){ //1s后获得镜子
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
}
总结:产生死锁的必要条件
互斥条件:
一个资源一次只能被一个进程使用
请求与保持条件:
进程已经保持了至少一个资源,但又提出了新的资源请求,而该资源 已被其他进程占有,此时请求进程被阻塞,但对自己已获得的资源保持不放。
不可剥夺条件:
进程所获得的资源在未使用完毕之前,不能被其他进程强行夺走,即只能 由获得该资源的进程自己来释放(只能是主动释放)。
循环等待条件:
指在发生死锁时,必然存在一个进程——资源的环形链,即进程集合{P0,P1,P2,···,Pn}中的P0正在等待一个P1占用的资源;P1正在等待P2占用的资源,……,Pn正在等待已被P0占用的资源。
这四个条件是死锁的必要条件,只要系统发生死锁,这些条件必然成立,而只要上述条件之一不满足,就不会发生死锁
死锁的避免与预防
死锁避免的基本思想:
系统对进程发出每一个系统能够满足的资源申请进行动态检查,并根据检查结果决定是否分配资源,如果分配后系统可能发生死锁,则不予分配,否则予以分配。这是一种保证系统不进入死锁状态的动态策略。
理解了死锁的原因,尤其是产生死锁的四个必要条件,就可以最大可能地避免、预防和解除死锁。只要打破四个必要条件之一就能有效预防死锁的发生:
● 打破互斥条件:改造独占性资源为虚拟资源,大部分资源已无法改造。
● 打破不可抢占条件:当一进程占有一独占性资源后又申请一独占性资源而无法满足,则退出原占有的资源。
● 打破占有且申请条件:采用资源预先分配策略,即进程运行前申请全部资源,满足则运行,不然就等待,这样就不会占有且申请。
● 打破循环等待条件:实现资源有序分配策略,对所有设备实现分类编号,所有进程只能采用按序号递增的形式申请资源。
死锁避免和死锁预防的区别:
死锁预防是设法至少破坏产生死锁的四个必要条件之一,严格的防止死锁的出现;而死锁避免则不那么严格的限制产生死锁的必要条件的存在,因为即使死锁的必要条件存在,也不一定发生死锁。死锁避免是在系统运行过程中注意避免死锁的最终发生。
package cn.imut7;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public static void main(String[] args) {
Lock2Test lock2Test = new Lock2Test();
new Thread(lock2Test).start();
new Thread(lock2Test).start();
new Thread(lock2Test).start();
}
}
class Lock2Test implements Runnable {
private int ticketNums = 10;
//定义lock锁
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();
}
}
}
}
Synchronized 与 Lock的对比
假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费
若仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中产品被消费者取走为止
若仓库有产品,则消费者可以取走产品,否则进行等待,直到仓库中放入产品
生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件
Java提供了几个方法解决线程通信问题
均为Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常
并发协作模型“生产者/消费者模式” ---> 管理法
生产者将数据放入缓冲区,消费者从缓冲区拿出数据
package cn.imut8;
//生产者-消费者模型:缓冲区解决
public class PCTest {
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++) {
System.out.println("生产了" + i + "只鸡");
synContainer.push(new Chicken(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) {
//若容器已满,则等待消费者
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 cn.imut9;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolTest {
public static void main(String[] args) {
//创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭连接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
标签:alt adl 缺陷 内部类 pool produce object 另一个 队列
原文地址:https://www.cnblogs.com/yfyyy/p/12661785.html