多线程(二)
线程安全问题
方式一 :同步代码块
* synchronized(同步监视器){
* //需要被同步的代码
* }
* 说明:1, 操作共享数据的代码,即为需要被同步的代码
* 2,共享数据 :多个线程同时操作的变量。比如 :ticket
* 3,同步监视器 ,俗称 :锁。任何一个类的对象,都可以充当锁。
* 要求 : 多个线程必须用同一把锁。
package com.kuang.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 acct;
int drawingMoney;
int nowMoney;
public Drawing(Account acct,int drawingMoney,String name){
super(name);
this.acct = acct;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
synchronized (acct){
//判断有钱没钱
if (acct.money - drawingMoney < 0) {
System.out.println("钱不够,取不了");
return;
}
//sleep 放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额
acct.money = acct.money - drawingMoney;
//手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(acct.name + "余额为:" + acct.money);
System.out.println(this.getName() + "手里的钱 : " + nowMoney);
}
}
}
方法二 : 同步方法
* 如果操作共享数据的代码完整的声明在一个方法中,我们不妨将次方法声明同步
package com.kuang.syn;
public class UnsafeBuyticket {
public static void main(String[] args) {
Buyticket buyticket = new Buyticket();
new Thread(buyticket,"我").start();
new Thread(buyticket,"你").start();
new Thread(buyticket,"黄牛").start();
}
}
class Buyticket implements Runnable{
private int ticketNum = 10;
boolean flag = true;
@Override
public void run() {
while(flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNum <= 0){
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNum--);
}
}
package com.kuang.syn;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 测试JUC安全类型的集合
* @author shiyu
* @date 2021-04-01 10:42
*/
public class TestJUC {
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();
}
}
}
方式三 lock锁
package com.kuang.Demo02;
/**
* 死锁 : 多个线程互相包着对方需要的资源,然后形成僵持
* @author shiyu
* @date 2021-04-01 10:52
*/
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 final 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 + "获得口红的锁");
}
}
}
}
package com.kuang.Demo02;
import java.util.concurrent.locks.ReentrantLock;
/**
* 测试lock锁
* @author shiyu
* @date 2021-04-01 11:12
*/
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();
}
}
}
}
// sychronized 和 lock 异同
// 相同: 二者都可以解决线程安全问题
// 不同 sychronized 机制在执行玩相应的同步代码以后,自动释放同步监视器
// lock 需要手动启动同步(lock())同时结束同步也需要手动的实现
管程法
package com.kuang.Demo02;
/**
* 测试 : 生产者消费者模型---> 利用缓冲区 :管程法
* @author shiyu
* @date 2021-04-01 11:25
*/
public class TestPC {
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.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 com.kuang.Demo02;
/**
* 测试生产者消费者问题2:信号灯法,标志位解决
* @author shiyu
* @date 2021-04-01 11:55
*/
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;
}
//20小时广告
@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++) {
tv.watch();
}
}
}
//产品 ----->TV
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;
}
}
线程池
package com.kuang.Demo02;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 测试线程池:
* ExecutorService : 真正的线程池接口
* Executors : 工具类、线程池的工厂类
* @author shiyu
* @date 2021-04-01 12:19
*/
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//ewFixedThreadPool 参数为线程池大小
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());
}
}