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 {

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

}


public class CounterThread extends Thread {
	
  Counter c;  


  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 CounterThread(Counter c) {
    this.c = c;
  }

  public void run() {

    c.count();
  	
  }		
	
}
Given these two 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
Last Modified December 2, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu