Synchronization: the problem. part 1

So far all the threads have run independently of each other. One thread did not need to know what another thread was doing. Sometimes, however, threads need to share data. In this case it is important to ensure that one thread doesn't change the data while the other thread is executing. The classic example is file access. If one thread is writing to a file while another thread is reading the file, it's likely that the thread that's reading the file will get corrupt data.

For example, consider the following toy problem:

public class Counter {

  private int count = 0;
  
  public void count() {
    int limit = count + 100;
    while (count++ != limit)  System.out.println(count); 
  }

}

public class CounterThread extends Thread {
    
  private Counter c;  

  public CounterThread(Counter c) {
    this.c = c;
  }

  public void run() {
    c.count();
  }     
    
}

public class CounterApp1 {

  public static void main(String[] args) {
  
    Counter c = new Counter();
    CounterThread ct1 = new CounterThread(c);
    ct1.start();

  } 

}

public class CounterApp2 {

  public static void main(String[] args) {
  
    Counter c = new Counter();
    CounterThread ct1 = new CounterThread(c);
    CounterThread ct2 = new CounterThread(c);
    ct1.start();
    ct2.start();

  } 

}

public class CounterApp3 {

  public static void main(String[] args) {
  
    Counter c1 = new Counter();
    Counter c2 = new Counter();
    CounterThread ct1 = new CounterThread(c1);
    CounterThread ct2 = new CounterThread(c2);
    ct1.start();
    ct2.start();

  } 

}

Given these classes what do you expect the output will be?

If you're reading this on the Web before class, I really want you to think about this problem before moving on to the next page. Give it some real thought; then run the program and see if that is indeed what happens.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 18, 2002