Java多线程之synchronized线程锁

时间:2021-06-13 12:51:12
 package org.study2.javabase.ThreadsDemo.sync;

 /**
* @Auther:GongXingRui
* @Date:2018/9/18
* @Description:synchronized线程锁
**/
public class TicketApp {
public static void main(String args[]) {
Ticket ticket = new Ticket();
Thread t1 = new Thread(ticket, "小红");
Thread t2 = new Thread(ticket, "明明");
t1.start();
t2.start();
}
} class Ticket implements Runnable {
int num = 20;
private boolean flag = true; @Override
public void run() {
while (flag) {
test();
}
} public synchronized void test() {
if (num <= 0) {
flag = false;
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "抢到票:" + num--);
}
}