Topic: 请大家帮我看看我用多线程写的冒泡法,有些错误

  Print this page

1.请大家帮我看看我用多线程写的冒泡法,有些错误 Copy to clipboard
Posted by: rongdf
Posted on: 2005-11-17 00:26

import java.lang.*;    
    
class mySort extends Thread{

  int[] unsort;
  int[] sorted;
  int[] hops = new int[1];
  Semaphore sem;
  //constructor
  protected mySort(int[] ia,int[] oa,int[] ns,Semaphore s){
    unsort = ia;
    sorted = oa;
    hops = ns;
    sem = s;
  }
        
  public void run(){        
    //using Semaphore to control threads
    do {
sem.P();
bubbleSort(unsort,sorted,hops);
sem.V();
} while (true);  
  }
  
  //the bubble sort implementation
  void bubbleSort(int[] numbers, int[] newnumber, int[] times){
  int i, j, temp;
  int length = numbers.length;
  
  //make a copy of array numbers to array newnumber
  for (i = 0; i <= (length-1); i++){
  newnumber[i] = numbers[i];   
  }

  for (i = (length-1); i >= 0; i--){
  for (j = 1; j <= i; j++){
  if (newnumber[j-1] > newnumber[j]){
  temp = newnumber[j-1];
  newnumber[j-1] = newnumber[j];
  newnumber[j] = temp;
  //hops increments by 1 when loop executes once
  hops[0]= hops[0] + 1;
  }
  }
  }
  }
}
    
class Assignment237{
  static Semaphore sem = new Semaphore(1);
    
//creat a new object
  public static void pbsort(int [] ia, int [] oa, int [] ns) {
    mySort s[] = new mySort[ia.length-1];
    
    //start threads based on the length of array to be sorted.
    //e.g.,there are n elements in the array,then start (n-1) threads
      for(int i = 0;i<(ia.length-2);i++){
        s[i] = new mySort(ia,oa,ns,sem);
        s[i].start();
      }    
  }    
}

class Test extends Assignment237 {

public static void main (String [] args) {
int [] ia = {4, 3, 2, 1};
int [] oa = new int[ia.length];
int [] ns = new int[1];

System.out.print("unsorted = ");
for(int i=0; i<ia.length; i++)
System.out.print(ia[i]+" ");
System.out.println("");

pbsort(ia, oa, ns) ;

System.out.print("sorted = ");
for(int i=0; i<oa.length; i++)
System.out.print(oa[i]+" ");

System.out.println(" hops = "+(ns[0]));
}
}

有2个问题我解决不了
1,不能把相关的array的值传进mySort class下的unsort,sorted,hops这几个变量中。
2,我试着用Semaphore去控制thread,但似乎会导致一个deadlock,我应该用得不怎么正确,各位DX能帮看看如何改进吗?


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923