同步函数以this为锁

本文通过示例代码详细解析了同步函数如何利用对象锁(this锁)确保线程安全,以及同步代码块和同步函数在不同场景下的应用与区别。
/*
	同步函数用的是this锁
	
	函数需要被对象调用。那么函数都有一个所属对象调用,就是this
	所以同步函数使用的锁是this

	
	通过该程序进行验证

	使用两个线程来卖票

	一个线程在同步代码块中
	一个线程在同步函数中
	都在执行卖票操作


*/

class Ticket implements	Runnable
{
	private int tick = 1000;
	
	//Object obj = new Object();

	boolean flag = true;

	public void run()
	{
		if(flag)//第一个进入的线程实行下面代码
		{
				while(true)
				{
					//synchronized(obj)//由于同步函数的是以this对象为锁的 此处如果使用obj对象作为锁
										//则不能实现同步 输出的数据会出现错误 程序的安全性不能得到保证
					synchronized(this)//和下面的show函数使用同样的锁 可以保证同步
					{
						if(tick>0)
						{
							try{Thread.sleep(40);}catch(Exception e){}
							System.out.println(Thread.currentThread().getName() +" .....code..."+ tick--);

						}
					}
				}
		}//第二个进入的代码实行下面代码
		else
			while(true)
				show();//this.show();
	
	}
	public synchronized void show()//同步函数 以this为锁
	{
		if(tick>0)
		{
			try{Thread.sleep(40);}catch(Exception e){}
			System.out.println(Thread.currentThread().getName() +" .....show..."+ tick--);
		}		
	}

}


class ThisLockDemo
{
	public static void main(String []args)
	{
		Ticket t = new Ticket();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
	
		t1.start();//开启第一个线程  但不一定马上执行
		
		t.flag = false;//改变标志
		try{Thread.sleep(40);}catch(Exception e){}//让主线程睡眠40毫秒  保证第一个线程先开始运行 且标志位改变

		t2.start();	
	}
}

在 Vue.js 中,处理同步和异步操作的函数或方法主要体现在以下几个方面: 在组件内部,Vue 提供了生命周期钩子函数来处理同步和异步逻辑。例如,在组件创建过程中,`created` 和 `mounted` 钩子常用于执行初始化逻辑,其中可能包含异步请求[^1]。例如: ```javascript export default { data() { return { items: [] }; }, created() { // 同步操作 this.items = [1, 2, 3]; }, mounted() { // 异步操作 setTimeout(() => { this.items.push(4); }, 1000); } }; ``` 此外,在 Vue 的 `watch` 中可以监听数据变化,并执行异步任务或复杂的同步逻辑。例如,当某个数据属性发生变化时,可以通过 `watch` 执行异步请求。 在 Vuex 中,处理同步和异步的方式更加明确。Vuex 的核心对象包括 `mutations` 和 `actions`:其中 `mutations` 用于处理同步操作,而 `actions` 用于处理异步操作。`actions` 可以通过 `commit` 调用 `mutations` 来更新状态。例如: ```javascript // Vuex mutations export default { addN(state, step) { state.count += step; } }; // Vuex actions export default { addAsync(context, step) { setTimeout(() => { context.commit('addN', step); }, 1000); } }; ``` 在组件中,可以通过 `this.$store.dispatch()` 调用 `actions`,例如: ```javascript methods: { asyncBtn() { this.$store.dispatch('addAsync', 5); } } ``` 为了简化操作,还可以使用 `mapActions` 辅助函数将 `actions` 映射为组件的 `methods`: ```javascript import { mapActions } from 'vuex'; methods: { ...mapActions(['addAsync']), asyncBtn() { this.addAsync(5); } } ``` 上述方法确保了在 Vue 和 Vuex 中可以有效地处理同步和异步操作,同时保持代码的清晰性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值