多种方式可以完成线程同步,传统方法是关键字 synchronized 完成的,可以是同步方法也可以是同步代码块
同步方法
@Data
@AllArgsConstructor
@NoArgsConstructor
class MyTheard4 implements Runnable{
private int ticket;
@Override
public void run() {
// test 方法是同步方法, 一次只能一个线程进入. 但是循环会有多个线程同时进入
while (this.getTicket() > 0){
test();
}
}
// 同步方法
public synchronized void test(){
// 1, 当剩余 1 张票的时候, 还是会有多个线程进入循环, 都等在同步方法外面
// 2, 这里再次判断就不会出现 0 或负数的情况
if (this.getTicket() <= 0){
return;
}
System.out.println(Thread.currentThread().getName() + ": " + ticket);
ticket--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test4 {
public static void main(String[] args) {
MyTheard4 myTheard4 = new MyTheard4(10);
new Thread(myTheard4, "线程A").start();
new Thread(myTheard4, "线程B").start();
new Thread(myTheard4, "线程C").start();
}
}
同步代码块
@Data
@AllArgsConstructor
@NoArgsConstructor
class MyTheard4 implements Runnable{
private int ticket;
@Override
public void run() {
while (this.getTicket() > 0){
test();
}
}
// 普通方法
public void test(){
// 同步代码块
synchronized (this) {
if (this.getTicket() <= 0) {
return;
}
System.out.println(Thread.currentThread().getName() + ": " + ticket);
ticket--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test4 {
public static void main(String[] args) {
MyTheard4 myTheard4 = new MyTheard4(10);
new Thread(myTheard4, "线程A").start();
new Thread(myTheard4, "线程B").start();
new Thread(myTheard4, "线程C").start();
}
}
标签:同步,java,void,getTicket,线程,test,public
From: https://www.cnblogs.com/hangychn/p/17178381.html