上邊是測試類,進行了快速排序 和工具類排序 建立了一個實現Runnable介面的對象,並傳遞參數 建立兩個線程並啟動線程 通過notify喚醒其他線程,通過wait停止自身線程,通過flag標誌為交替切換線程 ...
package com.swift; import java.util.Arrays; import java.util.Comparator; public class ArrayThread_Test { public static void main(String[] args) { /* * 已知一個數組[2,4,6,2,1,5],將該數組進行排序(降序,不能用工具類進行排序),創建兩條線程交替輸出排序後的數組,線程名自定義 */ Integer[] arr = new Integer[] { 2, 4, 6, 2, 1, 5 }; // 通過數組工具類排序 Arrays.sort(arr, new Comparator<Integer>() { @Override public int compare(Integer arg0, Integer arg1) { int num = arg1 - arg0; return num; } }); // 雙線快速排序 Integer[] arr2 = new Integer[] { 7, 2, 4, 16, 2, 13, 5 }; kuaisu(arr2, 0, arr2.length - 1); for (Integer i : arr2) { System.out.print(i + "~" + "\r\n"); } ArrayThread a = new ArrayThread(arr); Thread t1 = new Thread(a, "線程1"); Thread t2 = new Thread(a, "線程2"); t1.start(); t2.start(); } private static void kuaisu(Integer[] arr2, int left, int right) { if (left >=right)//當遞歸到只有一個數時停止 return; int key = arr2[left]; int i = left; int j = right; while (i != j) { while (arr2[j] > key && i < j) { j--; } while (arr2[i] <= key && i < j) { i++; } if (i < j) { int temp; temp=arr2[i]; arr2[i]=arr2[j]; arr2[j]=temp; } } arr2[left]=arr2[i]; arr2[i]=key; kuaisu(arr2, left, j - 1); kuaisu(arr2, i + 1, right); } }
上邊是測試類,進行了快速排序 和工具類排序
建立了一個實現Runnable介面的對象,並傳遞參數
建立兩個線程並啟動線程
package com.swift; public class ArrayThread implements Runnable{ Integer[] arr; int index=0; boolean flag=true; public ArrayThread(Integer[] arr) { this.arr=arr; } @Override public void run() { //for迴圈在多線程下不適合,雖然是一個對象的內容也會被執行多次迴圈,因為鎖在for迴圈裡邊 while (true) { synchronized (this) { if(index>=arr.length) { this.notify();//不喚醒其他線程為什麼出不去?虛擬機不停止 break; } System.out.println(Thread.currentThread().getName() + " 的輸出" + arr[index]); index++; if(flag) { flag=false; this.notify(); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else { flag=true; this.notify(); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
通過notify喚醒其他線程,通過wait停止自身線程,通過flag標誌為交替切換線程