多线程同步锁是谁

来源:互联网 发布:金属脚镣淘宝 编辑:程序博客网 时间:2024/05/16 06:39
/*
 * 需求:买票。
 */

/*
 * 同步函数使用的锁是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();
}
}
原创粉丝点击