线程同步之synchronized

为了避免临界区静态条件的发生,可以使用阻塞时的解决方案:synchronized,即俗称的对象锁

它采用互斥的方式让同一时刻至多只有一个线程能持有对象锁。

注意

虽然java中互斥和同步都可以采用synchronized关键字来完成,但它们还是有区别的

互斥是同一时刻只能有一个线程执行执行临界区代码。

同步时由于线程执行的先后,顺序不同,需要一个线程等待其它线程运行到某个点。

//synchronized加在对象上
package hello;
import java.util.*;
public class Main{

	public static void main(String[] args) throws InterruptedException{
		Test t=new Test();
		Thread t1=new Thread(()->{
		 for(int i=0;i<500;i++) {
			 t.increase();
		 }
		});
		Thread t2=new Thread(()->{
			for(int i=0;i<500;i++) {
				t.decrease();
			}
		});
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println(t.getCount());
	}
	
}
class Test{
	private static int count=0;
	public void increase() {
		synchronized(this) {
			count++;
		}
	}
	public void decrease() {
		synchronized(this) {
			count--;
		}
	}
	public int getCount() {
		return count;
	}
}
//synchronized加载非静态方法上
//public synchronized void test(){

//}等价于
//public void test(){
//    synchronized(this){
//}
//}
package hello;
import java.util.*;
public class Main{

	public static void main(String[] args) throws InterruptedException{
		Test t=new Test();
		Thread t1=new Thread(()->{
		 for(int i=0;i<500;i++) {
			 t.increase();
		 }
		});
		Thread t2=new Thread(()->{
			for(int i=0;i<500;i++) {
				t.decrease();
			}
		});
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println(t.getCount());
	}
	
}
class Test{
	private static int count=0;
	public synchronized void increase() {
			count++;
		
	}
	public synchronized void decrease() {

			count--;
		
	}
	public int getCount() {
		return count;
	}
}
//synchronized加在静态方法上相当于锁住了类对象
//public synchronized static void test(){
//
//}等价于
//public static void test(){
//    synchronized(Test.class){
//
//}
//}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值