import java.io.*; public class ThreadTeste extends Thread { private Point2d i; private char ch; public static void main(String[] args) { Point2d temp = new Point2d (10, 0); System.out.println ("Hello vaue of point is : " + temp); ThreadTeste tt = new ThreadTeste('a', temp); ThreadTeste tt2 = new ThreadTeste('b', temp); ThreadTeste tt3 = new ThreadTeste('c', temp); ThreadTeste tt4 = new ThreadTeste('d', temp); System.out.println ("Before Joins- Point is: " + temp); try{ tt.join(); } catch (Exception e) {} try{ tt2.join(); } catch (Exception e) {} try{ tt3.join(); } catch (Exception e) {} try{ tt4.join(); } catch (Exception e) {} System.out.println ("Goodbye- Point is: " + temp); } public ThreadTeste(char cParm, Point2d iparm) { //i = 10; i = iparm; ch = cParm; start(); //i += 2; //i.setX(i.getX() + 2); System.out.println ("From original thread " + ch + ", i: " + i); } public void run () { int y = 0; if (ch == 'a') y = 1; if (ch == 'b') y = 2; if (ch == 'c') y = -2; if (ch == 'd') y = -1; System.out.println ("From new thread " + ch + ", i: " + i); for (int j = 0 ; j < 1000000; j++) { // i.setX(i.getX() + y); modifyI2(y); } System.out.println ("Goodbye from thread " + ch + ", i: " + i); } // improper use of synchronized to avoid data collisions on // the shared variable i. The code snychronizes on the instances // of the thread class and not on the instance of i synchronized public void modifyI (int deta) { int temp = i.getX(); temp = temp + deta; i.setX(temp); } // this shows proper usage of synchronization on the instance // of the shared variable i public void modifyI2(int deta) { synchronized (i) { int temp = i.getX(); temp = temp + deta; i.setX(temp); } } }