java160108ThisLockDemo
莘聪
2023-12-01
/**
* 验证同步函数使用的锁是this
*/
package java160108;
/**
* @author LiZheng
*
*/
public class ThisLockDemo {
/**
* @param args
*/
public static void main(String[] args) {
Ticket3 ticket = new Ticket3();
Thread thread1 = new Thread(ticket);
Thread thread2 = new Thread(ticket);
//
Thread thread3 = new Thread(ticket);
//
Thread thread4 = new Thread(ticket);
thread1.start();
try {
Thread.sleep(10);//10毫秒
} catch (Exception e) {
e.printStackTrace();
}
ticket.flag=false;
thread2.start();
//
thread3.start();
//
thread4.start();
}
}
//要注意同步的代码是那一部分
//同步函数用的当前对象
class Ticket3 implements Runnable {
private int tick = 1000;
Object obj = new Object();
boolean flag=true;
@Override
public void run() {
if (flag) {
while (true) {
// synchronized同步代码块的关键字,参考火车卫生间是否有人
synchronized (this) {
if (tick>0) {
try {
// 此处会引发多线程的问题
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...code..." + tick--);
}
}
//
show();//this.show();
}
}else {
while (true) {
show();
}
}
}
public synchronized void show() {
if (tick > 0) {
try {
// 此处会引发多线程的问题
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...show..." + tick--);
}
}
}