Reeks 2:
Gedistribueerde Plants vs. Zombies
Java Concurrency: Counter example
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
Two threads using the same counter
THREAD 1 THREAD 2
1. retrieve c (0)
2. retrieve c (0)
3. increment c (1)
4. decrement c (-1)
5. save c (1)
6. save c (-1)
Synchronized Methods
- public synchronized void increment () { .. }
- No interleaving
- Changes to the state of the object are visible to all threads
Java Threads
public class MyRunnable implements Runnable {
public void run() {
// code to run in thread
}
};
(new Thread(new MyRunnable())).start();
public class MyThread extends Thread {
public void run() {
// code to run in thread
}
};
new MyThread().start();
Plants vs. Zombies
Streams
InputStream in = socket.getInputStream();
while(true) {
if (in.available() >= 4 {
int first = in.read();
int second = in.read();
.
.
.