java - How can I create separate output lines, depending on the Thread the output is coming from? -
i have program implements 2 different sort algorithms. testing both algorithms in parallel launching them in separate threads. able view results of sort operation, as taking place in each thread, , trying keep these results on same line (for each thread).
ex:
arr1= 3 5 8 11 16 ... (sort output thread 1)
arr2= 4 7 9 10 17 ... (sort output thread 2)
i have accomplishing thread.sleep(xxx)
after main logic runs, works when have 1 thread. if put delay in both threads displays this:
arr1=
arr2=arr1 [i] arr2[i] arr1[i+1] arr2[i+2] ...
in other words, output both sorts being displayed on same line.
here code:
import java.util.priorityqueue; class sortarebubblesort extends thread { int nre, min, max; public sortarebubblesort(int nre, int min, int max) { this.nre = nre; this.min = min; this.max = max; } public void run() { int[] x = new int[nre]; (int = 0; < x.length - 1; i++) x[i] = min + (int) (math.random() * ((max - min) + 1)); boolean domore = true; while (domore) { domore = false; (int = 0; < x.length - 1; i++) { if (x[i] > x[i + 1]) { int temp = x[i]; x[i] = x[i + 1]; x[i + 1] = temp; domore = true; } } } system.out.println("\nhere sorted array bubblesort:"); (int = 0; < x.length; i++) system.out.print(x[i] + " "); system.out.print("\n"); } } class sortareheapsort extends thread { int nre, min, max; public sortareheapsort(int nre, int min, int max) { this.nre = nre; this.min = min; this.max = max; } public void run() { int[] x = new int[nre]; (int = 0; < x.length - 1; i++) x[i] = min + (int) (math.random() * ((max - min) + 1)); priorityqueue<integer> pqueue = new priorityqueue<integer>(); (int w : x) pqueue.add(w); (int k = 0; k < x.length; k++) x[k] = pqueue.poll(); // print array system.out.println("\nhere sorted array heapsort:"); (int w : x) system.out.print(w + " "); } } public class testthread { public static void main(string args[]) { sortarebubblesort fir1; sortareheapsort fir2; fir1 = new sortarebubblesort(10, 1, 100); fir2 = new sortareheapsort(10, 100, 200); fir1.start(); fir2.start(); } }
any or guidance appreciated, thanks.
try make synchronized static method print array, first thread finishes job gets lock , release when prints entire array.
Comments
Post a Comment