java - The threads are not sharing the same data variable -
i'm new java. teacher gave me homework on multithreading in there 2 threads example , example1. example makes changes thread, , example1 reads it. when i'm implementing example1 thread not working properly.
example thread :
public class example extends thread { public int[] array = {2,1,0,5,9}; public void run(){ for(int i=0; i<array.length;i++){ array[i] = array[i]+i; system.out.println(getname()+" : "+array[i]); } } } example1 thread :
public class example1 extends example implements runnable { @override public void run(){ for(int i=0;i<array.length;i++){ system.out.println(getname()+" : "+array[i]); } } } the main :
public class testexample { public static void main(string[] args) { example t1 = new example(); t1.setname("t1"); t1.start(); example1 obj = new example1(); thread t2 = new thread(obj); t2.setname("t2"); t2.start(); } } and output :
t1 : 2 t1 : 2 t1 : 2 t1 : 8 t1 : 13 thread-1 : 2 thread-1 : 1 thread-1 : 0 thread-1 : 5 thread-1 : 9 thread example1 unable read changed values in int[] array when example has made changes int[] array. problem , how rectify it?
just make int[] array static.
public static int[] array = {2,1,0,5,9}; output :
t1 : 2 t1 : 2 t1 : 2 t1 : 8 t1 : 13 t2 : 2 t2 : 2 t2 : 2 t2 : 8 t2 : 13
Comments
Post a Comment