java 线程六-解决线程安全隐患问题-加锁

需求:
银行有一个金库
有两个储户分别存300元,每次存100,共存三次。

目的:判断该程序是否有安全问题,如果有该怎么解决?

如何找出安全隐患?
1,明确哪些代码是多线程运行代码。
2,明确共享数据。
3,明确多线程运行代码中哪些是操作共享数据的。
*/

/*
解决线程安全隐患问题,有两种方法:
1,使用synchronized(对象){同步代码块}
2,使用同步函数,即用synchronized来修饰函数,达到同步的目的。
class Bank
{
	private int sum;
	//Object obj=new Object();
	public synchronized void add(int x)
	{
		//synchronized(obj)
		//{
			try
			{
				Thread.sleep(10);
			}
			catch (InterruptedException e)
			{
			}
			sum=sum+x;
			System.out.println("sum"+sum);
		//}
	}
}

class Cus implements Runnable
{
	private Bank b=new Bank();
	public void run()
	{
		for(int i=0;i<3;i++)
		{
			b.add(100);
		}
	}

}



class BankDemo 
{
	public static void main(String[] args) 
	{
		Cus c=new Cus();
		Thread t1=new Thread(c);
		Thread t2=new Thread(c);
		t1.start();
		t2.start();
		//System.out.println("Hello World!");
	}
}

/*
当有多个生产者和消费者时:
1,需要使用while循环判断资源生产标识,是可生产的状态还是可取的状态。
2,需要使用notifyAll来唤醒所有线程,否则如果使用notify的话,会出现所有线程都等待(wait())的情况,程序一直等待,不再运行下去。
*/
class Resource
{
	private String name;
	private int num=0;
	boolean flag;
	public synchronized void set(String name)
	{
		//if(flag)
	    while(flag)
		try
		{
			this.wait();
		}
		catch (Exception e)
		{
		}
		this.name=name+"_"+num++;
		System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
		try
		{
			Thread.sleep(10);
		}
		catch (Exception e)
		{
		}
		flag=true;
		//this.notify();
		this.notifyAll();

	}
	public synchronized void get()
	{
		//if(!flag)
		while(!flag)
			try
			{
				this.wait();
			}
			catch (Exception e)
			{
			}
		System.out.println(Thread.currentThread().getName()+"消费者.............."+this.name);
		flag=false;
		//this.notify();
		this.notifyAll();
	}
}

class Producer implements Runnable
{
	private Resource r;
	Producer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while (true)
		{
			r.set("商品");
		}
	}
}

class Consumer implements Runnable
{
	private Resource r;
	Consumer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while (true)
		{
			r.get();
		}
	}
}

class ProducerConsumerDemo 
{
	public static void main(String[] args) 
	{
		Resource r=new Resource();

		Producer p=new Producer(r);
		Consumer c=new Consumer(r);

		Thread t1=new Thread(p);
		Thread t2=new Thread(p);
		Thread t3=new Thread(c);
		Thread t4=new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		System.out.println("Hello World!");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值