day014synchronized
Java 中的锁机制 程序安全
synchronized
多线程
- 多条道路解决单条道路无法满足的需求场景
- 线程之间并行由CPU随机处理
- io包下载网路图片 FileUtile.copyUrlToFile(URL,name)
- Runnable run 方法执行
- Callable call方法 创建ExciuitorServe 服务, submit 进去实例,接收返回值,shutdownnow关闭
- 代理模式
- 对象本身执行自己的事情,写字, 代理类在真实对象做的事基础上还要做自己的事,真实对象,和代理对象同时实现同一个接口需要
- lambda 一个接口只有一个方法时,实现它和这个方法只需要()->代替
- lambda 表达式演变 接口实现类》》静态内部类》》局部类》》匿名内部类》》()-> 表达式,函数式编程简化无用代码
- new Thread 线程新生 thread .start 线程就绪 运行 sleep wait 阻塞状态 由CPU随机分配调用 dead 线程结束,线程结束后不能重新start
- thread.getState NEW RUNNABLE TIMED_WITING TERMINATED
- thread .setPriority优先级 不一定优先级高的先执行
- thread.setDaemon(true) 守护线程 跟随同进程内的用户线程结束而结束
线程同步
synchronized synchronized
同步锁
package thread.syn;
/**
* @ Author :wwwzhqwww
* @ Date :Created in 18:19 2021/1/16
* @ Description:线程不安全的买车票
* @ Modified By:
* @Version: $version$
*/
public class UnsafeTicket {
public static void main(String[] args) {
Buyticket buyticket = new Buyticket();
new Thread(buyticket,"wwwww").start();
new Thread(buyticket,"ttttttttttt").start();
new Thread(buyticket,"gggg").start();
}
}
class Buyticket implements Runnable{
int ticketNum = 10;//一百张票
boolean flag = true;
@Override
public void run() {
while (flag){
buy();
}
}
private synchronized void buy(){//同步锁 买票不会出错
if(ticketNum <= 0){
flag = false;
return;
}
System.out.println(Thread.currentThread().getName()+"买到了第"+ticketNum+"张票");
ticketNum--;
try {//休眠放大场景不安全问题
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package thread.syn;
/**
* @ Author :wwwzhqwww
* @ Date :Created in 19:04 2021/1/16
* @ Description:
* @ Modified By:
* @Version: $version$
*/
public class UnsafeBack {
public static void main(String[] args) {
Account account =new Account(100,"marryMoney");
Drawing me = new Drawing(account,20,"我");
Drawing girl = new Drawing(account,100,"女朋友");
me.start();
girl.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 handMoney;
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
// this.handMoney = handMoney;
}
@Override
public void run() {
super.run();
synchronized(account){//同步锁块,默认锁的是this Drawing 此处应锁住account变化的属性
if(account.money - drawingMoney < 0){
System.out.println("money is less 无法取出那么多");
return;
}
try {//模拟延时同时取钱
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money -= drawingMoney;//账户的钱
handMoney += drawingMoney;//手里的钱
System.out.println("账户余额:"+account.money);
System.out.println(this.getName()+"手里的钱数:"+handMoney);
}
}
}