/*
* 需求:买票。
*/
/*
* 同步函数使用的锁是this
*
* 同步函数和同步代码块的区别:
*
* 同步函数的锁是固定的this
* 同步代码块的锁是任意的对象
* 静态方法当中没有this
* 静态的同步函数使用的锁是 该函数所属字节码文件对象,可以用 getClass方法获取,也可以用对象.class获取
*
* 建议使用同步代码块
*/
public class SynFunctionLock implements Runnable /* extends Thread */{
private int num = 500;
Object obj = new Object();
boolean flag = true;
public void run() {
/*System.out.println("this:" + this);*/
sale();
}
public void sale() {
if (flag) {
while (num > 0) {
synchronized ("ads") {//任意
if (num > 0) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ".....obj....." + num--);
}
}
}
}else{
while(num > 0){
this.show();
}
}
}
private synchronized void show() {//同步函数使用的锁是this
if (num > 0) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ".....function....." + num--);
}
}
}
class SynFunctionLockDemo {
public static void main(String[] args) {
SynFunctionLock t = new SynFunctionLock();// 创建一个线程任务对象
/*Class clazz = t.getClass();
Class claz = SynFunctionLock.class;*/
/*System.out.println("t:"+t);*/
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.flag=false;
t2.start();
}
}
相关文章
- 第十五章、Python多线程同步锁,死锁和递归锁
- Java多线程性能调优-Lock同步锁优化方法
- Android 多线程保证操作同步(同步锁的俩种)
- Java CAS同步机制 原理详解(为什么并发环境下的COUNT自增操作不安全): Atomic原子类底层用的不是传统意义的锁机制,而是无锁化的CAS机制,通过CAS机制保证多线程修改一个数值的安全性。
- 多线程 - 线程同步锁(lock、Monitor)
- JAVA之旅(十四)——静态同步函数的锁是class对象,多线程的单例设计模式,死锁,线程中的通讯以及通讯所带来的安全隐患,等待唤醒机制
- java 并发多线程显式锁概念简介 什么是显式锁 多线程下篇(一)
- python笔记9 线程进程 threading多线程模块 GIL锁 multiprocessing多进程模块 同步锁Lock 队列queue IO模型
- c#中多线程同步Lock(锁)的研究以及跨线程UI的操作
- java 多线程: Thread 并发访问-代码块同步synchronized {};String作为被锁的对象