对于Java中多线程互斥锁初步了解

来源:互联网 发布:数据库建模工具有哪些 编辑:程序博客网 时间:2024/06/05 06:29

慕课网上学习了java 多线程应用。
根据课中的 多线程数据争用 自己重写一遍代码

EnergySystem.class

package Energy;public class EnergySystem {    private final double energybox[] ;    EnergySystem(double totalE , int Boxquantity){        energybox = new double[Boxquantity];        for(int i = 0 ; i < energybox.length ; i++ ){            energybox[i] += totalE/Boxquantity ;            System.out.println("energybox[" + i + "] 分配到" + energybox[i] );            try {                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();}        }        System.out.println("能量分配完毕");    }    synchronized public void EnergyTrans(int from , int to , double amount){        if(energybox[from] < amount) {            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        energybox[from] -= amount ;        energybox[to] += amount ;        System.out.printf("从能量盒子[%d]中转移了%10.2f的能量到能量盒子[%d]中   " , from , amount , to);        System.out.println("总能量为" + getTotalEnergy());        try {            Thread.sleep(100);        } catch (InterruptedException e) {            e.printStackTrace();        }        notifyAll();    }    public double getTotalEnergy(){        double total = 0 ;        for (int i =0; i < energybox.length ;i++ ) {            total += energybox[i] ;        }        return total ;    }    public int getEnergyBoxLenght(){        return energybox.length;    }}

EnergyTransTask.class

package Energy;public class EnergyTransTask implements Runnable{    private EnergySystem es ;    private int fromBox ;    private double MaxAmount ;    private int DELAY = 10 ;    private int toBox ;    private double amount ;    public EnergyTransTask(EnergySystem es , int from ,double MaxAmount) {        this.MaxAmount = MaxAmount ;        this.fromBox = from ;        this.es = es ;    }    public void run(){        while(true){            toBox =(int) (es.getEnergyBoxLenght() * Math.random());            amount = MaxAmount * Math.random() ;            es.EnergyTrans(fromBox , toBox , amount);        try{            Thread.sleep(DELAY);        }catch(InterruptedException e){            System.out.println("EnergyTransTask interrupted");        }        }    }}

EnergySystemTest.class

package Energy;public class EnergySystemTest {    public static void main(String[] args) {        double MaxAmount = 5000.4f;        final double totalE = 100000 ;        final int BoxQuantity = 100 ;        EnergySystem es = new EnergySystem(totalE , BoxQuantity);        for (int j = 0; j < BoxQuantity; j++) {            EnergyTransTask est = new EnergyTransTask(es, j , MaxAmount);            Thread t = new Thread(est , "tt"+j);            t.start();        }    }}

总结 :
1.通过synchronized关键字对方法加上互斥锁解决数据争用问题。
2.为了缩小锁粒度,可以在方法中synchronized代码块加锁

private finall Object Objectf ;synchronized(Objectf){...}

3 .努力学。

0 0