Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 请大家帮我看看我用多线程写的冒泡法,有些错误
rongdf





发贴: 3
积分: 0
于 2005-11-17 00:26 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
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能帮看看如何改进吗?




我有一点感想和初学者们同享(原创)

话题树型展开
人气 标题 作者 字数 发贴时间
3317 请大家帮我看看我用多线程写的冒泡法,有些错误 rongdf 2368 2005-11-17 00:26

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   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