java 同步的两种方法

搬家后的博客链接: IT客栈 www.itkezhan.org

1.ReentrantLock(重入锁)可以加多层锁的意思。

用法

class X{
	private final ReentrantLock lock = new ReentrantLock();
	
	public void m()
	{
		lock.lock();
		try{
			//需要保证线程安全的代码编写区域		
		}
		finally
		{
			lock.unlock();  //上面的代码执行完了之后对其进行解锁。以便其他线程可以访问。
		}
	}
}


2.synchronized(英文翻译:同步的)


同步代码块

synchronized(obj)
{
	//这里是编写同步代码块。即需要保护的代码区域  “临界区”  
}


同步方法

class test{
	public synchronized void t()
	{
		//这个方法不能让多个线程同时访问。保证了某一个时刻只有一个线程执行它。
	}

}



========================================================================================


//ReentrantLock


import java.util.concurrent.locks.ReentrantLock;

class a{
	
		private final ReentrantLock l = new ReentrantLock();
		

				public void t()
				{
					l.lock();
					try
					{
						System.out.print("同一时间只有一个调用我\t");
						System.out.println(Thread.currentThread().getName());
					} 
					finally
					{
						l.unlock();
					}
				}

		

}


class myThread extends Thread{
	
	a a1;
	
	myThread(a a1)
	{
		this.a1 = a1;
	}

    @Override
	public void run()
	{
		for(int i = 0 ; i< 10 ; i++)
		{

			a1.t();
			
			try
			{
				myThread.sleep(1);
			}
			catch(InterruptedException e)
			{
				
			}
		}
	}

}


public class test{

	public static void main(String[] args)
	{
		a a1 = new a();
		myThread m1 = new myThread(a1);
		myThread m2 = new myThread(a1);
		
		m1.start();
		m2.start();
	}

}





class a{
//synchronized 同步代码块实例	



		public void t()
		{
				System.out.print("同一时间只有一个调用我\t");
				System.out.println(Thread.currentThread().getName());
		} 
	

}


class myThread extends Thread{
	
	a a1;
	
	myThread(a a1)
	{
		this.a1 = a1;
	}

	public void run()
	{
		for(int i = 0 ; i< 10 ; i++)
		{
			synchronized(a1)
			{
				a1.t();
			}
			try
			{
				this.sleep(1);
			}
			catch(InterruptedException e)
			{
				
			}
		}
	}

}


public class test{

	public static void main(String[] args)
	{
		a a1 = new a();
		myThread m1 = new myThread(a1);
		myThread m2 = new myThread(a1);
		
		m1.start();
		m2.start();
	}

}







//synchronized 方法实例

class a{
	
 	public synchronized void t()
	{
			System.out.print("同一时间只有一个调用我\t");
			System.out.println(Thread.currentThread().getName());
	} 

}


class myThread extends Thread{
	
	a a1;
	
	myThread(a a1)
	{
		this.a1 = a1;
	}

	public void run()
	{
		for(int i = 0 ; i< 10 ; i++)
		{
			a1.t();
			try
			{
				this.sleep(1);
			}
			catch(InterruptedException e)
			{
				
			}
		}
	}

}


public class test{

	public static void main(String[] args)
	{
		a a1 = new a();
		myThread m1 = new myThread(a1);
		myThread m2 = new myThread(a1);
		
		m1.start();
		m2.start();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值