Java开发网 |
注册 |
登录 |
帮助 |
搜索 |
排行榜 |
发帖统计
|
您没有登录 |
» Java开发网 » Java SE 综合讨论区
打印话题 寄给朋友 订阅主题 |
作者 | 请大家帮我看看我用多线程写的冒泡法,有些错误 |
rongdf
发贴: 3 积分: 0 |
于 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能帮看看如何改进吗? 我有一点感想和初学者们同享(原创) |
话题树型展开 |
人气 | 标题 | 作者 | 字数 | 发贴时间 |
3317 | 请大家帮我看看我用多线程写的冒泡法,有些错误 | rongdf | 2368 | 2005-11-17 00:26 |
已读帖子 新的帖子 被删除的帖子 |
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 |