Java Programming Home Page: Archive: Message #124

Date: Nov 09 2000 09:37:49 EST
From: "Java Programming" <javaProgramming-owner@listbot.com>
Subject: synchronized output,sw409

Hi All,
Here is a thread example that shows you
how to perform synchronized output.
Note how the system.out is wrappered in
a synchronized block. This makes sure that
only one thread can print at a time.

Cheers!
 - DL
public class ThreadTest 
	implements Runnable {
	
  Thread t = new Thread(this);
  int threadTestNumber = 0;
  public static int n=1000;

  ThreadTest() {
  	t.start();
  	threadTestNumber = n;
  	n++;
  }
  public void sleep(long time) {
  	try {
  		Thread.sleep(time);
  	}
  	catch(InterruptedException e) {
  		System.out.println(e);
  	}
  }
  
  public void run() {
    while (true) {
      synchronized(System.out) {
    	System.out.println(
  	 		 (
  	 	threadTestNumber+":"+
  	 	 new java.util.Date()).toString());
	   }
		sleep((int)(Math.random()*1000));
  	}
  }
  public static void main(String args[]) {
  	for (int i=0; i < 9000; i++)
  		 new ThreadTest();
  }
}