# 线程同步机制 形成条件:队列+锁 ## cynchronized 隐式 线程不安全案列 ```java public class bank { public static void main(String[] args) { Account account = new Account("9527",100); Drawing you=new Drawing(account,50,"w"); Drawing Girlfriend=new Drawing(account,100,"girlfriend"); you.start(); Girlfriend.start(); } } class Account{ String name=""; int money=0; public Account(String name, int money) { this.name = name; this.money = money; } } class Drawing extends Thread{ Account account; int drawingmoney = 0; int remainingmoney=0; Drawing(Account account,int drawingmoney,String name){ super(name); this.account = account; this.drawingmoney = drawingmoney; this.remainingmoney = remainingmoney; } @Override public void run() { if(account.money-drawingmoney<0){ System.out.println(account.name+"取不了钱"); return;} try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } account.money-=drawingmoney; remainingmoney+=drawingmoney; System.out.println(account.name + "余额为:"+account.money + ""); System.out.println(Thread.currentThread().getName() + "手中的钱"+remainingmoney); } } ``` ```java import java.util.ArrayList; import java.util.List; public class unsafetest { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for (int i = 0; i < 1000 ; i++ ) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } System.out.println(list.size()); } } ``` 修改后 ```java //使用同步方法 public class mytest { public static void main(String[] args) { buytickets buytickets=new buytickets(); new Thread(buytickets,"小明").start(); new Thread(buytickets,"小红").start(); new Thread(buytickets,"小张").start(); } } class buytickets implements Runnable { private int tickets=20; private int flag=1; @Override public void run() { while (flag==1) { try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void buy() throws InterruptedException { if(tickets<=0){flag=0; return;} Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"拿到第"+tickets--+"张票"); } } ``` ```java //同步块 public class bank { public static void main(String[] args) { Account account = new Account("9527",100); Drawing you=new Drawing(account,50,"w"); Drawing Girlfriend=new Drawing(account,100,"girlfriend"); you.start(); Girlfriend.start(); } } class Account{ String name=""; int money=0; public Account(String name, int money) { this.name = name; this.money = money; } } class Drawing extends Thread{ Account account; int drawingmoney = 0; int remainingmoney=0; Drawing(Account account,int drawingmoney,String name){ super(name); this.account = account; this.drawingmoney = drawingmoney; this.remainingmoney = remainingmoney; } @Override public void run() { synchronized (account){ if(account.money-drawingmoney<0){ System.out.println(account.name+"取不了钱"); return;} try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } account.money-=drawingmoney; remainingmoney+=drawingmoney; System.out.println(account.name + "余额为:"+account.money + ""); System.out.println(Thread.currentThread().getName() + "手中的钱"+remainingmoney); } } } ``` 锁的对象就是变化的量,需要增删改的量 ```java public class unsafetest { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for (int i = 0; i < 1000 ; i++ ) { new Thread(()->{ synchronized (list){ list.add(Thread.currentThread().getName());} }).start(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } } ``` ## lock 显式 ```java import java.util.concurrent.locks.ReentrantLock; public class lock { public static void main(String[] args) { test test=new test(); new Thread(test).start(); new Thread(test).start(); new Thread(test).start(); } } class test implements Runnable { private int tickets=10; //定义lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while(true){ try { lock.lock(); if (tickets>=0){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(tickets--); } else break; } finally { lock.unlock(); } } } } ``` # 生产者消费者问题 ## 管程法 ```java public class testpc { public static void main(String[] args) { syncontainer syncontainer=new syncontainer(); new productor(syncontainer).start(); new consumer(syncontainer).start(); } } class productor extends Thread{ syncontainer container; productor(syncontainer container){ this.container = container; } @Override public void run() { for(int i = 0; i <100;i++){ System.out.println("生产了第"+i+"只鸡"); container.push(new chicken(i)); } } } class consumer extends Thread { syncontainer container; 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; 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; } } ``` ## 信号灯法 ```java public class testpc2 { public static void main(String[] args) { TV tv=new TV(); new watcher(tv).start(); new player(tv).start(); } } class player extends Thread { TV tv=new TV(); 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; watcher(TV tv){ this.tv = tv; } @Override public void run() { for (int i = 0; i < 20; i++) { this.tv.watch(); } } } class TV{ String program; boolean flag=false; public synchronized void play( String program){ if(flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("演员表演了"+program); this.notifyAll(); this.program = program; this.flag = !this.flag; } public synchronized void watch(){ if (!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("观众观看了"+program); this.notifyAll(); this.flag = !this.flag; } } ``` ## 线程池 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class testpoor { 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.execute(new Mythread()); service.shutdown(); } } class Mythread implements Runnable { @Override public void run() { for (int i = 0; i < 1; i++) { System.out.println(Thread.currentThread().getName() + ""+i); } } } ```