java - unable to get proper result using threads -
suppose have 3 arrays different length. want sort these 3 arrays 3 different threads.
i wrote below code this. write or there happening wrong. giving me correct result , values of arrays merging other array's values:
i added syncronized display method, again getting incorrect result.
public class threaddemo implements runnable { private int[] arr; private string[] s_arr; public threaddemo(int arr[]) { this.arr=arr; } @override public void run() { getsorted(arr); try{ thread.sleep(2000); }catch(interruptedexception e){ e.printstacktrace(); } } private void getsorted(int[] arr) { (int = 0; < arr.length; i++) { (int j = 0; j < (arr.length-1) - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } display(arr); } public static void display(int[] a){ for(int i:a) system.out.print(i+" "); system.out.println(); } public static void main(string[] args) { int arr1[]={8,25,9,12,13,17,1}; int arr2[]={38,2,19,12,3,17,16}; int arr3[]={3,22,9,1,34,17,86}; threaddemo demo1=new threaddemo(arr1); thread t1=new thread(demo1); threaddemo demo2=new threaddemo(arr2); thread t2=new thread(demo2); threaddemo demo3=new threaddemo(arr3); thread t3=new thread(demo3); t1.start(); t2.start(); t3.start(); } } output #1: here values mixing.
1 8 9 12 13 17 25 2 3 12 16 17 1 3 9 17 22 34 86 19 38 output #2: correct
1 8 9 12 13 17 25 2 3 12 16 17 19 38 1 3 9 17 22 34 86 output #3: incorrect
1 8 9 12 13 17 25 2 1 3 3 12 9 16 17 17 22 19 38 34 86 public static synchronized void display(int[] a){ for(int i:a) system.out.print(i+" "); system.out.println(); }
your arrays in correct order. printed results being interleaved because prints happening on different threads.
sort arrays on each thread , print results once threads have finished.
Comments
Post a Comment