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

来源:互联网 发布:endnote mac 编辑:程序博客网 时间:2024/06/05 22:03
需求:
银行有一个金库
有两个储户分别存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!");}}

0 0
原创粉丝点击