JAva上機第14週タスク1スレッドの練習
3187 ワード
/*
*
*
* Copyright (c) 2011,
* All rights reserved.
* :
* :
* :2012 11 29
* :x1.0
*
* :
* : RandomNumber, 10 n, n 。
* Thread1( Thread ) Thread2( Runnable ) ,
* Thread1 , 。Thread2 , 。
* TestThread, ,
* :
*
*/
// Test
package xue;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
Thread th2 = new Thread(thread2);
thread1.start();
th2.start();
}
}
//RandomNumber
package xue;
public class RandomNumber {
public int []num;
public int n;
RandomNumber()
{
n = (int)(Math.random()*10 + 10);
num = new int[n];
}
public int[] getNum() {
return num;
}
public void produceRd()
{
for(int x = 0; x < num.length; x++)
{
num[x] = (int)(Math.random()*10 + 10);
}
}
}
// Thread1
package xue;
public class Thread1 extends Thread {
public void run()
{
int temp;
RandomNumber randomNum = new RandomNumber();
int[] rdn = new int[randomNum.n];
randomNum.produceRd();
for(int i = 0; i < randomNum.n; i++)
{
rdn[i] = randomNum.num[i];
}
for(int x = 0; x < rdn.length - 1; x++)
for(int y = 0; y < rdn.length - x - 1; y++)
{
if(rdn[y] > rdn[y+1])
{
temp = rdn[y];
rdn[y] = rdn[y+1];
rdn[y+1] = temp;
}
}
System.out.println(" :");
for(int num : rdn)
{
System.out.println(" :---" + num);
}
}
}
// Thread2( Runnable )
package xue;
public class Thread2 implements Runnable {
private static void sort(int[] a, int first, int last)
{
int i = first;
int j = last;
int middle = a[first]; //
while (true) {
while (++i < last - 1 && a[i] < middle)
;
while (--j > first && a[j] > middle)
;
if (i >= j) {
break;
}
swap(a, i, j);
}
a[first] = a[j];
a[j] = middle;
if (first < j) {
sort(a, first, j);
}
if (i < last) {
sort(a, i, last);
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void run() {
RandomNumber randomNum = new RandomNumber();
randomNum.produceRd();
int[] rdn1 = randomNum.getNum();
sort(rdn1, 0, rdn1.length);
System.out.println(" :");
for(int num : rdn1)
{
System.out.println(" :--------" + num);
}
}
}
実行結果: