Universität Paderborn - Home Universität Paderborn
Die Universität der Informationsgesellschaft

Parallel Programming WS 2014/2015 - File Atomic.java

class Data {
    private int x, y;
    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setX(int val) {
        x = val;
    }

    public void setY(int val) {
        y = val;
    }
}

public class Atomic {
    public static void main(String[] args) {
        final Data d = new Data();

        Runnable r1 = new Runnable() {
            public void run() {
                try {
                    Thread.sleep((int) (Math.random() * 100));
                } catch (InterruptedException e) {}
                d.setX(d.getX() + d.getY());
            }
        };
        Runnable r2 = new Runnable() {
            public void run() {          
                try {
                    Thread.sleep((int) (Math.random() * 100));
                } catch (InterruptedException e) {}
                d.setY(d.getX() - d.getY());
            }
        };

        for (int i = 0; i < 100; i++) {
            d.setX(2);
            d.setY(5);
            new Thread(r1).start();
            new Thread(r2).start();
            try { // wait a second
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
            System.out.println("x = " + d.getX() + " y = " + d.getY());
        } 
    }
}

Generiert mit Camelot | Probleme mit Camelot? | Geändert am: 27.10.2014