多线程
-
同步
-
多个线程操作同一个资源 并发
-
对象等待池 队列
-
锁
-
降低性能
-
性能倒置
-
线程挂起
-
死锁
- 相互等待对方资源
- 产生条件
- 一个资源只能被一个进程使用
- 请求和保持条件
- 不剥夺条件
- 循环等待条件
//测试死锁 public class DeadLock { public static void main(String[] args){ new Make(0,"小红").start(); new Make(1,"小明").start(); } } //口红 class Lipstick {} //镜子 class Mirror {} class Makeup extends Thread { static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); int choice; String girlName; public Makeup(String name,choice){ this.girlName = name; this.choice = choice; } public void run(){ if(choice==0){ synchronized (lipstick){ System.out.println(this.girlName()+"获得口红"); Thread.sleep(1000); //死锁 synchronized(mirror){ System.out.println(this.girlName()+"获得镜子"); } } } if(choice==1){ synchronized (mirror){ System.out.println(this.girlName()+"获得镜子"); Thread.sleep(1000); synchronized(lipstick){ System.out.println(this.girlName()+"获得口红"); } } } } }
-
-
队列 + 锁 = 线程同步(synchronized)
//不安全的门票 public class UnsafeBuyTicket { public static void main(String[] args){ BuyTicket buy = new BuyTicket(); new Thread(buy,"可恶的黄牛党1").start(); new Thread(buy,"可恶的黄牛党2").start(); new Thread(buy,"学生").start(); } } class BuyTicket implements Runnable { //票数 private int ticketNums = 10; private boolean flag = true; //买票 public void run(){ while(flag){ try{ Thread.sleep(1000); }catch(InterruptedException i){ i.printStackTrace(); } buy(); System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums--+"张票"); } } //判断是否有票 private synchronized void buy() throws InterruptedException{ if(ticket<=0){ flag = false; //return; } } }
银行取钱
// public class UnSafeBank { public static void main(String[] args){ Account account = new Account(1000,"湖州宁"); WithDraw drawMoney = new WithDraw("HU",1000,account); WithDraw drawMoney1 = new WithDraw("ZO",1000,account); drawMoney.start(); drawMoney1.start(); } } //账户 class Account { double money; String name; public Accout(double money,String name){ this.money = money; this.name = name; } } //取钱操作类 class WithDraw extends Thread { private final Account account; private final double drawingMoney; //private double nowMoney; public WithDraw(String name,double drawingMoney,Account account){ super(name); this.account = account; this.drawingMoney = drawingMoney; } public void run(){ synchronized(account){ if(isMoney){ try{ Thread.sleep(1000); }catch(InterruptedException i){ i.printStackTrace(); } this.account.money = this.account.money - this.drawingMoney; System.out.println(this.getName()+"取钱成功,取钱"+this.drawingMoney); System.out.println(this.account.name+"账户余额为:"+this.account.money); } } } //判断余额是否充足 public boolean isMOney(){ if(this.account.money==0&&this.account.money<this.drawingMoney){ System.out.println("取钱失败,余额不足!"); return false; } else{ return true; } } }
import java.util.List; import java.util.ArrayList; //线程不安全的集合 public class UnSafeList { public static void main(String[] args){ List<String> list = new ArrayList<String>(); for(int i = 0; i < 10000;i++){ new Thread(()->{ synchronized(list){ list.add(Thread.currentThread().getName()); } }).start(); } System.out.println(list.size()); } }
import java.util.concurrent.CopyOnWriteArrayList; //测试JUC并发 JUC线程安全类 public class TestJUC { public static void main(String[] args){ CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); for(int i = 0; i < 1000; i++){ new Thread(()->{ list.add(Thread.currentThread().getName()) }).start(); } } }
-
Lock 锁
import java.util.concurrent.ReentrantLock; //Lock加锁测试 public class TestLock{ public static void main(String[] args){ TicketLock ticketLock = new TicketLock(); new Thread(ticketLock,"a").start(); new Thread(ticketLock,"b").start(); new Thread(ticketLock,"c").start(); } } class TicketLock implements Runnable{ private int ticketNums = 10; //定义锁 private final ReentrantLock lock = new ReentrantLock(); public void run(){ while(true){ try{ lock.lock();//加锁 try{ Thread,sleep(1000); }catch(InterruptedException i){ i.printStackTrace(); } if(ticketNums<=0){ break; }else{ System.out.println(ticketNums--); } }finally{ lock.unlock();//解锁 } } } }
//测试生产消费者问题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 { private Tv tv; public Player(Tv tv){ this.tv = tv; } public void run(){ for(int i = 0; i < 20; i++){ if(i<10){ this.tv.play("喜羊羊与灰太狼"); }else{ this.tv.play("猫和老鼠"); } } } } //观众 class Watcher extends Thread { private Tv tv; public Watcher(Tv tv){ this.tv = tv; } 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 i){ i.printStackTrace(); } } System.out.println("演员表演了:"+this,voice); this.flag = !this.flag; this.voice = voice; //通知观看 this.notify(); } public synchronized void watch(){ if(flag){ try{ this.wait();//等待 }catch(InterruptedException i){ i.printStackTrace(); } } System.out.println("观众观看了"+this.voice); this.flag = !this.flag; //通知表演 this.notify(); } }
-
-
-
通信问题
-
线程协作
-
生产者消费者模式
-
wait()等待
-
notify()唤醒
-
管程法
//测试: 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; } public void run(){ for(int i = 0; i < 1000; 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 < 1000; i++){ container.pop(); System.out.println("消费了"+i+"只鸡"); } } } //产品 class Chicken { private 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 i){ i.printStackTrace(); } } chikens[count] = chicken; count++; //产品不够 唤醒生产 this.notify(); } public synchronized void pop(){ if(count==0){ //产品消费完 通知生产 try{ this.wait(); }catch(InterruptedException i){ i.printStackTrace(); } } count--; Chicken chicken = chickens[count]; return chicken; //唤醒消费 this.notify(); } }
-
-
高级主体
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors //测试线程池 public class TestPool { public static void main(String[] args){ //1.创建服务,创建线程城池 //newFixedThreadPool 差数为:线程池大小 ExecutorService service = Executors.newFixedThreadPool(3); //执行 service.execute(new ThreadPool()); service.execute(new ThreadPool()); service.execute(new ThreadPool()); //关闭 service.shutDown(); } } class ThreadPool implements Runnable { public void run(){ for(int i = 0; i < 3; i++){ System.out.println(Thread.currentThread().getName()); } } }
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; //测试Callable public class TestCall{ public static void main(String[] args){ FutureTask<Integer> task = new FutureTask<Integer>(new MyThread()); new Thread(task).start(); try{ System.out.println(task.get()); }catch(InterruptedException i){ i.printStackTrace(); }catch(ExecutionException e){ e.printStackTrace(); } } } class MyThread implement Callable<Integer> { public Integer call(){ System.out.println("Callable"); return 100; } }