多任务:边吃饭边玩手机
但是本质上大脑在同一时间依旧只做了一件事情
程序是静态的,进程是程序执行的过程,一个进程可以有多个线程,真正执行的是线程
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i <20 ; i++) {
System.out.println("我在看代码");
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1=new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 2000; i++) {
System.out.println("我在学习多线程");
}
}
}
总结:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2(String url ,String name){
this.url=url;
this.name=name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloade(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args){
TestThread2 t1=new TestThread2("https://www.51wendang.com/doc/c4ea862180e68ca5a074899dfd85634723c2e5ec/10","2.jpg");
t1.start();
}
}
//下载器
class WebDownloader{
//下载方法
public void downloade(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
//创建线程方式一:实现runnable接口,重写run()方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread3 implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i <20 ; i++) {
System.out.println("我在看代码"+i);
}
}
public static void main(String[] args) {
//创建runnbale接口的实现类对象
TestThread3 testThread3=new TestThread3();
//创建线程对象,通过线程开启我们的线程,代理
Thread thread=new Thread(testThread3);
thread.start();
new Thread(testThread3).start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程"+i);
}
}
}
继承Thread类
实现Runnable接口
多个线程操作同一个对象案例
public class TestThread4 implements Runnable{
//票数
private int ticketNums=10;
@Override
public void run() {
while(true){
if (ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取Thread的名字
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
}
}
public static void main(){
TestThread4 testThread4=new TestThread4();
new Thread(testThread4,"小明");
new Thread(testThread4,"老师");
new Thread(testThread4,"黄牛");
}
}
//模拟龟兔赛跑
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(300);
} 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) {
Race race=new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
package Callable;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class TestCallable implements Callable {
private String url;//网络图片地址
private String name;//保存的文件名
public TestCallable(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) throws ExecutionException, InterruptedException {
TestCallable t1=new TestCallable("https://www.51wendang.com/doc/c4ea862180e68ca5a074899dfd85634723c2e5ec/10","1.jpg");
TestCallable t2=new TestCallable("https://www.51wendang.com/doc/c4ea862180e68ca5a074899dfd85634723c2e5ec/10","2.jpg");
TestCallable t3=new TestCallable("https://www.51wendang.com/doc/c4ea862180e68ca5a074899dfd85634723c2e5ec/10","3.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future r1=ser.submit(t1);
Future r2=ser.submit(t2);
Future r3=ser.submit(t3);
//获取结果
boolean rs1=r1.get();
boolean rs2=r2.get();
boolean rs3=r3.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异常");
}
}
}
Callable的好处:
静态代理模式总结:
好处:
public class StacticProxy {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("123");
}
}).start();
new WeddingCompany(new You()).HappyMarry();
new WeddingCompany(new You());
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("结婚前");
}
}
函数式接口的定义
public class lamdba {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda2");
}
}
public static void main(String[] args) {
ILike like=new Like();
like.lambda();
like=new Like2();
like.lambda();
//4.局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda3");
}
}
like=new Like3();
like.lambda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类,注意分号
like=new ILike(){
@Override
public void lambda() {
System.out.println("i like lambda4");
}
};
like.lambda();
//6.用Lambda简化
like=()->{
System.out.println("i like lambda5");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda1");
}
}
lambda简化
ILove love=null;
//1.lambda简化
love=(int a)->{
System.out.println("i love you-->"+a);
}
//简化参数类型
love=(a)->{
System.out.println("i love you-->"+a);
}
//简化括号
love=a->{
System.out.println("i love you-->"+a);
}
//简化花括号
love=a->System.out.println("i love you-->"+a);
love.love(521);
总结:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XOV919Ln-1636557470627)(E:\桌面\文档\javaweb\多线程.assets\image-20211109150003879.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PxiJTi9e-1636557470628)(E:\桌面\文档\javaweb\多线程.assets\image-20211109150143641.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9XFBcUJX-1636557470630)(E:\桌面\文档\javaweb\多线程.assets\image-20211109150334204.png)]
//测试stop
//1.建议线程正常停止-->利用次数,不建议死循环
//2.建议使用标志位-->设置一个标志位
//3.不要使用stop或者destory等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{
//1.设置一个标志位
private boolean flag=true;
@Override
public void run() {
int i=0;
while(flag){
System.out.println("run......ing"+i++);
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop=new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if (i==900){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
注意:
//模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable{
//票数
private int ticketNums=10;
@Override
public void run() {
while(true){
if (ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取Thread的名字
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
TestSleep testThread4=new TestSleep();
new Thread(testThread4,"小明").start();
new Thread(testThread4,"老师").start();
new Thread(testThread4,"黄牛").start();
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep2 {
public static void main(String[] args) {
//倒计时
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印当前系统时间
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();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num=10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
注意:
//测试礼让线程
//礼让不一定成功,看CPU心情
public class TestYied {
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()+"线程停止执行");
}
}
注意:
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 < 1000; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
public class TestSate {
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();
}
}
});
//观察状态
Thread.State state=thread.getState();
System.out.println(state);
//观察启动后
thread.start();//启动线程
state=thread.getState();
System.out.println(state);//Run
while(state!=Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state=thread.getState();//更新线程状态
System.out.println(state);
}
}
}
//测试线程的优先级
public class TestPriority {
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(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(1);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
总结:
java提供一个线程调度器来监控程序中启动后就绪状态的所有线程,线程调度器按照优先级决定应该调度那个线程来执行
线程的优先级用数学表示,范围从1~10.
使用以下方式改变或获取优先级
优先级的设定要在start()调度前
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度(性能倒置)
//测试守护线程
//上帝守护你
public class TestDamon {
public static void main(String[] args) {
God god=new God();
Youe you=new Youe();
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("上帝保佑着你");
}
}
}
//你
class Youe implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
}
}
注意:
多个线程操作同一个资源
并发:同一个对象被多个线程同时操作
处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象。这时候我们就需要线程同步,线程同步,其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
形成条件:队列+锁
锁机制:synchronized
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性﹐在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。
存在以下问题:
//不安全的买票
//线程不安全
public class UnsafeBuy {
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 (flag){
buy();
}
}
private void buy(){
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
有人拿到0,-1,线程是不安全的
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account=new Account(100,"结婚基金");
Drawing you=new Drawing(account,50,"你");
Drawing girlFrend=new Drawing(account,100,"girlFrend");
you.start();
girlFrend.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(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep可以放大问题的发生性
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);
}
}
import java.util.ArrayList;
import java.util.List;
//线程不安全集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list =new ArrayList<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();
}
System.out.println(list.size());
}
}
同步方法:
同步块:
问题解决:
加上synchronized,在方法前
//不安全的买票
//线程不安全
public class UnsafeBuy {
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 (flag){
buy();
}
}
//synchronized 同步方法,锁的是this
private synchronized void buy(){
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
synchronized默认锁定是this,锁的对象是变化的量
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account=new Account(100,"结婚基金");
Drawing you=new Drawing(account,50,"你");
Drawing girlFrend=new Drawing(account,100,"girlFrend");
you.start();
girlFrend.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
@Override
public void run() {
synchronized (account){
//判断有没有钱
if(account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep可以放大问题的发生性
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);
}
}
}
//死锁:多个线程互相抱着对方需要的资源,形成死锁
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0,"回顾面馆");
Makeup g2=new Makeup(1,"白雪公主");
g1.start();
g2.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+"获得口红的锁");
}
}
}
}
}
//死锁:多个线程互相抱着对方需要的资源,形成死锁
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0,"回顾面馆");
Makeup g2=new Makeup(1,"白雪公主");
g1.start();
g2.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(2000);
}
synchronized (lipstick){//一秒后想获口红
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
产生死锁的四个必要条件:
注意:只要想办法破其中一个或者多个就可以避免产生死锁
ReentrantLock
可重入锁
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2=new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
//测试锁
class TestLock2 implements Runnable{
int ticketNums=10;
@Override
public void run() {
while(true){
if(ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else{
break;
}
}
}
}
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2=new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
//测试锁
class TestLock2 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();
}
}
}
}
生产者消费者模式
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件.
所以,Java提供了几个方法解决线程之间的通信问题
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
nofityAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级高的线程优先调度 |
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IIIegalMoniTorStateException
并发协作模型“生产者/消费者模式”—>管程法
//测试:生产者消费者模型-->利用缓存区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Priductor(container).start();
new Consumer(container).start();
}
}
//生产者
class Priductor extends Thread{
SynContainer container;
public Priductor(SynContainer container){
this.container=container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产l"+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){
//通知消费者消费,生产者等待
}
//如果没有满,我们就需要丢入产品
chickens[count]=chicken;
count++;
//可以通知消费者消费
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count==0){
//等待生产者生产,消费者等待
}
//如果可以消费
count--;
Chicken chicken=chickens[count];
//吃完了,通知生产者生产
return chicken;
}
}
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
信号灯法
//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPc2 {
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("快乐大本营");
}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++) {
this.tv.watch();
}
}
}
//产品-->节目
class TV{
//演员表演,观众等待
//观众观看,演员等待
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;
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池,参数为线程池大小
ExecutorService service= Executors.newFixedThreadPool(10);
//执行
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());
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程的创建
public class ThreaadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask=new FutureTask(new MyThread3());
new Thread(futureTask).start();
try {
Integer 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("MyThreadd1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThreadd2");
}
}
//3.实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThreadd3");
return 100;
}
}
线程同步 synchronized
线程扩展
锁
xecutorService service= Executors.newFixedThreadPool(10);
//执行
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());
}
}
# 17.总结
~~~java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程的创建
public class ThreaadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask futureTask=new FutureTask(new MyThread3());
new Thread(futureTask).start();
try {
Integer 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("MyThreadd1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThreadd2");
}
}
//3.实现Callable接口
class MyThread3 implements Callable{
@Override
public Integer call() throws Exception {
System.out.println("MyThreadd3");
return 100;
}
}
线程同步 synchronized
线程扩展
锁
此文章来源于哔哩哔哩狂神说学习笔记