线程同步
并发:同一个对象被多个线程同时操作,如上万人同时抢100张票,两个银行同时取钱。
线程同步:是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面的线程使用完毕,下一个线程再使用。
锁机制:由于同一进程的多个线程共享同一块存储空间,在带来方便的同时也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制(synchronized),当一个线程获得对象的排它锁,独占资源,其它线程必须等待,使用后释放锁即可。存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题
三大不安全案例
-
不安全的买票
//不安全的买票 //线程不安全,有同一张票被多个人买,还有-1 public class UnsafeBuyTicket implements Runnable{ //票 private int ticket = 10; boolean flag = true;//外部停止方式 @Override public void run() { //买票 while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } private void buy() throws InterruptedException { //判断是否有票 if(ticket<=0){ flag = false; return; } //模拟延时 Thread.sleep(100); //买票 System.out.println(Thread.currentThread().getName()+"拿到"+ticket--); } public static void main(String[] args) { UnsafeBuyTicket station = new UnsafeBuyTicket(); Thread thread1 = new Thread(station,"小明"); Thread thread2 = new Thread(station,"小红"); Thread thread3 = new Thread(station,"小强"); thread1.start(); thread2.start(); thread3.start(); } }
-
不安全的取钱
//不安全的取钱
//两个人去银行取钱
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,"女朋友");
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;
}
//取钱
public void run(){
//判断有没有钱
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
nowMoney = nowMoney+drawingMoney;
System.out.println(Thread.currentThread().getName()+"手里的钱:"+nowMoney);
System.out.println(account.name+"余额为"+account.money);
}
}
-
线程不安全集合
//线程不安全集合 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(()->{ list.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(3000); System.out.println(list.size()); } }
同步方法
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:
synchronized方法和synchronized块
同步方法:public synchronized void method(int args){}
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
缺陷:若将一个大的方法声明为synchronized将会影响效率
-
安全的买票
public class UnsafeBuyTicket implements Runnable{ //票 private int ticket = 10; boolean flag = true;//外部停止方式 @Override public void run() { //买票 while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } //synchronized同步方法,锁的是this private synchronized void buy() throws InterruptedException { //判断是否有票 if(ticket<=0){ flag = false; return; } //模拟延时 Thread.sleep(100); //买票 System.out.println(Thread.currentThread().getName()+"拿到"+ticket--); } public static void main(String[] args) { UnsafeBuyTicket station = new UnsafeBuyTicket(); Thread thread1 = new Thread(station,"小明"); Thread thread2 = new Thread(station,"小红"); Thread thread3 = new Thread(station,"小强"); thread1.start(); thread2.start(); thread3.start(); } }
-
安全的取钱
锁的对象应该是变化的量,需要增删改的对象
//两个人去银行取钱
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,"女朋友");
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;
}
//取钱
//synchronized 默认锁的是this
public void run(){
synchronized (account){
//判断有没有钱
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
nowMoney = nowMoney+drawingMoney;
System.out.println(Thread.currentThread().getName()+"手里的钱:"+nowMoney);
System.out.println(account.name+"余额为"+account.money);
}
}
}
-
安全的集合
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(3000); System.out.println(list.size()); } }
测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}