Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Thread sharing in Timer

By: a guest on Dec 17th, 2012  |  syntax: Java  |  size: 1.05 KB  |  views: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import java.awt.event.ActionEvent;
  2. import java.awt.event.ActionListener;
  3. import java.text.MessageFormat;
  4.  
  5. import javax.swing.Timer;
  6.  
  7. public class Sandbox {
  8.   private static int i = 0;
  9.   public static void main(String[] args) {
  10.     ActionListener listener = new ActionListener() {
  11.       @Override public void actionPerformed(ActionEvent event) {
  12.         i++;
  13.         System.out.println(MessageFormat.format(
  14.             "{0}: {1} ms", i, System.currentTimeMillis() % 1000000));
  15.       }
  16.     };
  17.     System.out.println(MessageFormat.format(
  18.         "start: {0} ms", System.currentTimeMillis() % 1000000));
  19.     Timer timer = new Timer(1000, listener);
  20.     timer.start();
  21.     timer = new Timer(1000, listener); /* replace timer */
  22.     timer.start();
  23.     try {
  24.       Thread.sleep(3000);
  25.     } catch (InterruptedException e) {
  26.       e.printStackTrace();
  27.     }
  28.     System.exit(0);
  29.   }
  30. }
  31.  
  32. /*
  33. output:
  34.  
  35. start: 849,378 ms
  36. 1: 850,574 ms
  37. 2: 850,574 ms     <-- exact same millisecond
  38. 3: 851,569 ms
  39. 4: 851,570 ms     <-- same millisecond, slight delay
  40. */
clone this paste RAW Paste Data