标签:-o throws des term class 同步 sync string try
package www.it.com.thread;
/**
* @author wangjie
* @date 2019/11/21 11:42
* @description 证明同步函数使用的是this锁 一个线程使用代码块,一个使用同步函数
* @company 石文软件有限公司
*/
public class SynchronizedDemo implements Runnable {
private Integer count = 100;
private boolean flag = true;
//自定义锁
private Object object = new Object();
@Override
public void run() {
if (flag) {
while (true) {
synchronized (object) {
if (count > 0) {
try {
Thread.sleep(40);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName() + ",出售 第" + (100 - count + 1) + "张票.");
count--;
}
}
}
} else {
while (true) {
sale();
}
}
}
public synchronized void sale() {
if (count > 0) {
try {
Thread.sleep(40);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName() + ",出售 第" + (100 - count + 1) + "张票.");
count--;
}
}
public static void main(String[] args) throws InterruptedException {
SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
Thread thread1 = new Thread(synchronizedDemo, "线程一");
Thread thread2 = new Thread(synchronizedDemo, "线程二");
thread1.start();
Thread.sleep(100);
synchronizedDemo.flag = false;
thread2.start();
}
}
当同步代码块使用object锁时运行发生线性安全问题
将同步代码块变成this锁,因为和同步函数使用的是同一把锁this,所以不会发生线程安全问题
标签:-o throws des term class 同步 sync string try
原文地址:https://www.cnblogs.com/wang66a/p/12069284.html