First understanding of concurrency in multithreading
What is concurrency: we simulate an example of ticket grabbing
public class TextThread3 implements Runnable {
//票数
private int tickName=10;
@Override
public void run() {
while (true){
//如果票数小于10跳出循环
if(tickName<=0){
break;
}
try {
//延时操作,防止cpu将全部资源分配给同一个人
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Thread.currentThread().getName():获取当前线程的名字
System.out.println(Thread.currentThread().getName()+"拿到了第"+tickName--+"张票");
}
}
public static void main(String[] args) {
TextThread3 textThread3=new TextThread3();
new Thread(textThread3, "小明").start();
new Thread(textThread3, "老师").start();
new Thread(textThread3, "黄牛党").start();
}
}
Run the code and we will find that: without thread lock, the teacher and Xiao Ming grabbed the 4th ticket at the same time
Solution: add thread lock, and use the flag to stop the thread
*I don't know the reference of the flag bit: https://blog.csdn.net/moerduo0/article/details/113803579
Modified code: We encapsulate the code for buying tickets into a new method buy(), and add a thread lock synchronized to it
public class TextThread3 implements Runnable {
//票数
private int tickName=10;
//标志位
boolean flag =true;
@Override
public void run() {
//当flag为false停止循环
while (flag){
try {
//买票
buy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//线程锁
private synchronized void buy() throws Exception{
//判断是否有票没配票时flag为false
if(tickName<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到了第"+tickName--+"张票");
}
public static void main(String[] args) {
TextThread3 textThread3=new TextThread3();
new Thread(textThread3, "小明").start();
new Thread(textThread3, "老师").start();
new Thread(textThread3, "黄牛党").start();
}
}
Effect: It is normal now