当多个线程同时对一个资源进行访问的时候,就会出现以下问题:
package com.bes.mybatis_plus.Test1;
public class TestThread4 implements Runnable{
//总火车票数
private int ticketNums = 10;
@Override
public void run() {
while(true){
if(ticketNums <= 0){
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + "拿到了第"+ ticketNums-- + "张票");
}
}
public static void main(String[] args) {
TestThread4 testThread4 = new TestThread4();
//三个线程同时抢票
new Thread(testThread4, "潘狗子").start();
new Thread(testThread4, "阿米立卡").start();
new Thread(testThread4, "黄牛").start();
}
}
执行结果:
"黄牛拿到了第9张票
阿米立卡拿到了第10张票
潘狗子拿到了第9张票
阿米立卡拿到了第7张票
黄牛拿到了第8张票
潘狗子拿到了第6张票
阿米立卡拿到了第4张票
黄牛拿到了第3张票
潘狗子拿到了第5张票
潘狗子拿到了第2张票
黄牛拿到了第1张票
阿米立卡拿到了第2张票
Process finished with exit code 0
可以看到,第9张票,第2张票,同时被多个人拿到
这与现实情况矛盾,所以在多线程同时访问同一个资源时,会出现问题,所以需要对应的解决办法:加上锁解决并发问题
package com.bes.mybatis_plus.Test1;
public class TestThread4 implements Runnable {
//总火车票数
private int ticketNums = 10;
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (this) {
if (ticketNums <= 0) {
break;
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
}
}
}
public static void main(String[] args) {
TestThread4 testThread4 = new TestThread4();
new Thread(testThread4, "潘狗子").start();
new Thread(testThread4, "阿米立卡").start();
new Thread(testThread4, "黄牛").start();
}
}
执行结果:
潘狗子拿到了第10张票
黄牛拿到了第9张票
阿米立卡拿到了第8张票
阿米立卡拿到了第7张票
黄牛拿到了第6张票
潘狗子拿到了第5张票
潘狗子拿到了第4张票
黄牛拿到了第3张票
阿米立卡拿到了第2张票
潘狗子拿到了第1张票
Process finished with exit code 0
这只是很简单的一个加锁的应用,此文章只是介绍多线程出现的问题,想知道更多解决方法,后会有期