synchronized lock

本文通过一个具体的Java程序示例,展示了如何使用synchronized关键字来实现线程间的同步操作,防止多个线程同时修改共享资源导致的问题。示例中创建了三个线程,它们共享一个计数器变量并对其进行递减操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

public class MyThread extends Thread
{
	/**
	 * 
	 * @param name thread's name
	 */
	public MyThread(String name)
	{
		super(name);
	}

	// goods cnt
	static int cnt = 20;

	// lock
	static Object ob = "ZENGWENFENG";

	public void run()
	{
		while (cnt > 0)
		{
			synchronized (ob)
			{
				if (cnt > 0)
				{
					System.out.println(getName() + " --- NO." + cnt + " --- ");
					cnt--;
				}
				else
				{
					System.out.println("Game Over!");
				}
			}

			try
			{
				sleep(1000);//sleep 1000ms
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}



package test;

public class ZzzTest
{
	/**
	 * java synchronized lock
	 * 
	 * @author ZengWenFeng
	 */
	public static void main(String[] args)
	{
		//
		MyThread station1 = new MyThread("thread_zwf_01");
		MyThread station2 = new MyThread("thread_zwf_02");
		MyThread station3 = new MyThread("thread_zwf_03");

		//
		station1.start();
		station2.start();
		station3.start();
	}
}


thread_zwf_01 --- NO.20 --- 
thread_zwf_03 --- NO.19 --- 
thread_zwf_02 --- NO.18 --- 
thread_zwf_02 --- NO.17 --- 
thread_zwf_01 --- NO.16 --- 
thread_zwf_03 --- NO.15 --- 
thread_zwf_01 --- NO.14 --- 
thread_zwf_03 --- NO.13 --- 
thread_zwf_02 --- NO.12 --- 
thread_zwf_03 --- NO.11 --- 
thread_zwf_02 --- NO.10 --- 
thread_zwf_01 --- NO.9 --- 
thread_zwf_02 --- NO.8 --- 
thread_zwf_01 --- NO.7 --- 
thread_zwf_03 --- NO.6 --- 
thread_zwf_02 --- NO.5 --- 
thread_zwf_01 --- NO.4 --- 
thread_zwf_03 --- NO.3 --- 
thread_zwf_02 --- NO.2 --- 
thread_zwf_03 --- NO.1 --- 
Game Over!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

spencer_tseng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值