/* File: Counter04.java This time the Counter class has an int array called sharedArray[]. Methods in private inner classes have access to sharedArray[]. Both threads can read from and write to sharedArray. Instead of counting down 10, 9, 8, ... as before, the threads print out values from sharedArray[]. Twist: whichever thread finishes first, trashes the array (by storing negative values in the array) so the other thread prints out "garbage". */ import javax.swing.*; import java.awt.Font ; public class Counter04 { // data members are accessible to methods of inner classes. int [] sharedArray ; private class Window1 implements Runnable { int start = 10 ; int xpos = 0 ; int ypos = 0 ; Window1() { // do nothing, use default values } Window1(int n) { start = n ; // count down from n } Window1(int n, int x, int y) { start = n ; // set all parameters xpos = x ; ypos = y ; } public void run() { try { // same old, same old // JFrame frame = new JFrame( "Start value =" + start ); JLabel label = new JLabel("Hello, Java!", JLabel.CENTER ); label.setFont( new Font("Serif", Font.BOLD, 36) ) ; frame.getContentPane().add( label ); frame.setSize( 300, 300 ); frame.setLocation( xpos, ypos ); frame.setVisible( true ); Thread.sleep(1000) ; // print from array instead of printing i .. for(int i = start ; i >= 0 ; i--) { label.setText( Integer.toString(sharedArray[i]) ) ; Thread.sleep(2000) ; } label.setText("Kaboom!") ; // when we are done, trash the array. No call to // Thread.sleep(), so this is really fast. // for (int i = 0 ; i < sharedArray.length ; i++) { sharedArray[i] = -i ; } Thread.sleep(1000) ; } catch ( InterruptedException e ) { System.out.println("Oh look! an exception!") ; } } } public void doThis() { // initialize sharedArray... // sharedArray = new int[100] ; for (int i = 0 ; i < sharedArray.length ; i++) { sharedArray[i] = 3 * i ; } // same as before // Window1 w1 = new Window1(13) ; Thread t1 = new Thread(w1) ; t1.start() ; Window1 w2 = new Window1(9, 400, 0) ; Thread t2 = new Thread(w2) ; t2.start() ; try { t1.join() ; t2.join() ; } catch ( InterruptedException e ) { System.out.println("Oh look! an exception!") ; } System.exit(0) ; } public static void main( String[] args ) { Counter04 obj = new Counter04() ; obj.doThis() ; } }