悲观锁
一上来就加锁,没有安全感, 每次只能一个线程进入,访问完毕后访问完毕后再解锁,性能较差。
乐观锁
一开始是不上锁的,认为是没有问题的,大家一起跑, 等要出现线程安全的时候, 才开始控制, 线程安全,性能较好。
取100份礼物,小红, 小明,两人同时发送,当剩下的礼品小于10的时候,不再发出 利用多线程模拟该过程并将线程的名称打印出来,并最后再控制台分别打印出小红,小明各自送出多少份礼物。 拿100份礼品出来。
public class SendGiftTest {public static void main(String[] args) {//取100份礼物,小红, 小明,两人同时发送,当剩下的礼品小于10的时候,不再发出// 利用多线程模拟该过程并将线程的名称打印出来,并最后再控制台分别打印出小红,小明各自送出多少份礼物。//拿100份礼品出来final ArrayList<String> gift = new ArrayList<>();String[] names = {"口红", "包包", "鲜花", "剃须刀", "皮带","手带"};final Random random = new Random();for (int i = 0; i < 100; i++) {gift.add(names[random.nextInt(names.length - 1)]+(i+1));}System.out.println(gift);final SendGift sendGift = new SendGift(gift, "小明");sendGift.start();final SendGift sendGift1 = new SendGift(gift, "小红");sendGift1.start();try {sendGift.join();sendGift1.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(sendGift.getCount());System.out.println(sendGift1.getCount());}
}
public class SendGift extends Thread {private List<String> gift;private int count;public SendGift(List<String> gift , String name) {super(name);this.gift = gift;}@Overridepublic void run() {//小明,小红发礼物//实现线程安全问题//注意:锁唯一对象String name = Thread.currentThread().getName();final Random random = new Random();while (true) {synchronized (gift) {if (gift.size() < 10) {break;}String rs = gift.remove(random.nextInt(gift.size()));System.out.println(name + "发出了:" +rs + "");count++;}}}public int getCount() {return count;}public void setCount(int count) {this.count = count;}}