面向对象-多线程(同步函数的锁是this与静态同步函数的锁是class)

同步函数使用的是哪一个锁呢?
函数需要被对象调用,那么函数都有一个所属对象引用,就是this。。

所以同步函数使用的锁是this。

代码:

class Demo implements Runnable
{
	private int t=200;
	Object obj = new Object();
	boolean flag = true;
	public void run () {
		if(flag) {//同步代码块
			while(true) {
				synchronized (this) {
					if(t>0) {
						try {Thread.sleep(10);} catch (Exception e) {}
						System.out.println(Thread.currentThread().getName()+"-code:"+t--);
					}
				}
			}
		}
		else {//同步函数
			while(true)
				show();
		}
	}
	public synchronized void show() {//this
		if(t>0) {
			try {Thread.sleep(10);} catch (Exception e) {}
			System.out.println(Thread.currentThread().getName()+"--show:"+t--);
		}
	}
}

public class code
{
    public static void main(String[] args) {
    	Demo t = new Demo();
    	Thread t1 = new Thread(t);
    	Thread t2 = new Thread(t);
    	t1.start();
    	try {Thread.sleep(10);} catch (Exception e) {}
    	t.flag = false;
    	t2.start();
    }
}
如果同步函数被静态修饰后,使用的锁是什么呢?
通过验证,发现不在是this,因为静态方法中不可以定义this。

静态进内存:内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class  该类对象的类型是Class

静态的同步方法:使用的锁是该方法所在类的字节码文件对象。  类名.class 字节码文件对象是唯一的。

用static修饰->对象在方法区中
不用static修饰->对象在堆内存中

代码:

class Demo implements Runnable
{
	private static int t=200;
	boolean flag = true;
	public void run () {
		if(flag) {
			while(true) {
				synchronized (Demo.class) {
					if(t>0) {
						try {Thread.sleep(10);} catch (Exception e) {}
						System.out.println(Thread.currentThread().getName()+"-code:"+t--);
					}
				}
			}
		}
		else {
			while(true)
				show();
		}
	}
	public static synchronized void show() {//class
		if(t>0) {
			try {Thread.sleep(10);} catch (Exception e) {}
			System.out.println(Thread.currentThread().getName()+"--show:"+t--);
		}
	}
}

public class code
{
    public static void main(String[] args) {
    	Demo t = new Demo();
    	
    	Thread t1 = new Thread(t);
    	Thread t2 = new Thread(t);
    	t1.start();
    	try {Thread.sleep(10);} catch (Exception e) {}
    	t.flag = false;
    	t2.start();
    }
}

死锁:同步中嵌套同步,锁不同。

Jion:当线程执行到了B线程的 .join()方法时,A就会等待。等B线程都执行完,A才会执行。

join可以用来临时加入线程执行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值