关于synchronized的认识一

生气synchronized的认识一[慢慢深入]

一:修饰方法 

1,synchronized  mothed

这种同步只是针对当前new出来的对象锁定,也就是说:new出1个当前对象,无论你开多少线程去访问该对象中任意一个synchronized 方法,都得等前一个调用结束后才能调用,顺序不定。 当然你new 多个对象,多个线程并且分别调用不同的方法,则synchronized 是没有作用的。这时候就得看2了。。。

2,synchronized static  mothed

加static是在上面的基础上,个人认为是给当前对象加了一个全局锁,不论你是new出不同对象还是直接在线程中调用。该类的synchronized只能由一个线程去调用,全局锁定,该线程结束后其他线程继续去调用,顺序不定。

 

贴上两个测试类:

public class TestSynchronized {
	
	public static void main(String[] args) throws InterruptedException {
		
		TestThread testThread=new TestThread();
		new Thread(testThread).start();
		new Thread(testThread).start();
		TestThread testThread1=new TestThread();
		new Thread(testThread1).start();
		new Thread(testThread1).start();
		
	}
	
	public static final synchronized void synch1(){
		System.out.println("1 star!"+new Date().getTime());
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("1 over!"+new Date().getTime());
	}
	
	public static final synchronized void synch2(){
		System.out.println("2 star!"+new Date().getTime());
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("2 over!"+new Date().getTime());
	}
	
}
public class TestThread implements Runnable {
	
	private TestSynchronized t=new TestSynchronized();
	
	public TestThread(){}
	
	public TestThread(TestSynchronized tt){
		t=tt;
	}
	
	private int i=0;
	
	public void run() {
		this.i++;
		try {
			if(i%2==0){
				System.out.println(i+"调用第一个方法");
				t.synch1();
				System.out.println(i+"调用结束。。。。。");
			}else{
				System.out.println(i+"调用第二个方法");
				t.synch2();
				System.out.println(i+"调用结束。。。。。");
			}
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


 

二:方法块

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值