同步方法:我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块
同步方法:public synchronized void method(int args){}
缺陷:若将一个大的方法申明为synchronized将会影响效率
同步块:synchronized(Obj){}
Obj称之为同步监视器。
监视的对象为需要进行增、删、改、查的对象
1.加synchronized的买票安全
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 ticketNums =10;
boolean flag=true;
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException{
//判断是否有票
if(ticketNums<=0){
return;
}
//买票
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
2.银行账户加synchronized(){},需要进行修改的对象
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 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() {
synchronized(account){
//判断是否还有钱
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,钱取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额-你取的钱
account.money=account.money-drawingMoney;
//你手里的钱
nowMoney=nowMoney+drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
}
3.加synchronized(){}
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized(list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(1000);
System.out.println(list.size());
}
}