java中的synchronized与semaphore

synchronized:

java中线程同步关键字,其实是代码或对象的互斥访问。对于sychronize方法, 同一时刻只能有一个线程调用,返回后其余线程才可使用。对于synchronized代码段,需当前线程执行完该段代码后,其余线程才可执行。锁的wait() 需要notify() 方法唤醒,才可解除阻塞。容易产生死锁问题。


semphore:

可用于处理生产者与消费者问题,代码如下:

package chapter1;

import java.util.concurrent.Semaphore;
public class ProducerConsumer {

	/**
	 * @param args
	 */
    int[] BoundedBuffer;
    final static int BufferCapacity = 30, TOTAL = 100;
    Semaphore put_sema = new Semaphore(30);
    Semaphore get_sema = new Semaphore(0);
    int put_index = 0, get_index = 0, put_count = 0, get_count = 0;
    public static void main(String[] args) {
		// TODO Auto-generated method stub
    	ProducerConsumer pc  = new ProducerConsumer();
    	Thread p = new Thread(pc.new Producer());
    	Thread c = new Thread(pc.new Consumer());
    	p.start();
    	c.start();

	}
	
	class Producer implements Runnable
	{
		public void run()
		{
			while(true)
			{
				try
				{
					put_sema.acquire();
					put_index = (put_index + 1) % BufferCapacity;
					put_count++;
					get_sema.release();
					System.out.println(" item " + put_count + "produced");
					if(put_count >= TOTAL)
						break;
					
					Thread.sleep(10);
				}
				catch(InterruptedException e)
				{
					Thread.interrupted();
				}
				
				
			}
		 }	
			
		}
		
		class Consumer implements Runnable
		{
			public void run()
			{
				while(true)
				{
					try
					{
						get_sema.acquire();
						get_index = (get_index + 1) % BufferCapacity;
						get_count++;
						put_sema.release();
						System.out.println(" item " + get_count + " consumered ");
						if(get_count >= TOTAL)
							break;
						
						Thread.sleep(30);
					}
					catch(InterruptedException e)
					{
						Thread.interrupted();
					}
				}
			}
		}
}
	


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值