private Egg egg = new Egg();
public PutEggThread(Plate plate){
this.plate = plate;
}
public void run(){
for(int i = 0; i < PUT_EGG_TIMES; i++){
plate.putEgg(egg);
}
}
}
static class GetEggThread extends Thread{
private static final int GET_EGG_TIMES = 5;
private Plate plate;
public GetEggThread(Plate plate){
this.plate = plate;
}
public void run(){
for(int i = 0; i < GET_EGG_TIMES; i++){
plate.getEgg();
}
}
}
private static class Egg{
}
public static void main(String[] args) {
try {
Plate plate = new Plate();
Thread putEggThread = new PutEggThread(plate);
Thread getEggThread = new GetEggThread(plate);
putEggThread.start();
getEggThread.start();
putEggThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package demo;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
public class Sort {
/**
* 冒泡排序
* 若前一个元素大于后一个元素,将两者交换。
*/
public int[] bubbleSort(int[] iAry) {
int aryLen = iAry.length;
for (int i = 1; i < aryLen; i++) {
for (int j = 0; j < aryLen - i; j++) {
if (iAry[j] > iAry[j + 1]) {
swap(iAry, j, j + 1);
}
}
}
return iAry;
}
/**
* 选择排序
*/
public int[] selectSort(int[] iAry) {
int aryLen = iAry.length;
int index = 0;
for (int i = 1; i < aryLen; i++) {
index = 0;
for (int j = 1; j <= aryLen - i; j++) {
if (iAry[j] > iAry[index]) {
index = j;
}
}
swap(iAry, index, aryLen - i);
}
return iAry;
}
/**
* 插入排序
* 将一个记录插入到已排好序的有序表中,从而得到一个新的记录数增1的有序表。
*/
public int[] insertSort(int[] iAry) {
int aryLen = iAry.length;
for (int i = 1; i < aryLen; i++) {
for (int j = 0; j < i; j++) {
if (iAry[j] > iAry[i]) {
swap(iAry, i, j);
}
}
}
return iAry;
}
/**
* 快速排序
* 思路:选择中间数作为基准,然后i从左向右找到第一个大于等于这个基准的数,j从右向左找到第一个小于等于该基准的数,直到i>=j,交换这两个数。
* 然后递归对左边i个数和右边n-1-i个数进行相同排序。
*/
public int[] quickSort(int[] iAry, int left, int right) {
if (left < right) {
int midNum = iAry[(left + right) / 2];
int i = left - 1;
int j = right + 1;
while (true) {
while (iAry[++i] < midNum);
while (iAry[--j] > midNum);
if (i >= j) {
break;
}
swap(iAry, i, j);
}
quickSort(iAry, left, i - 1);
quickSort(iAry, j + 1, right);
}
return iAry;
}
private int[] createAry() {
Random rand = new Random();
int[] ary = new int[5];
for (int i = 0; i < ary.length; i++) {
ary[i] = rand.nextInt(100);
}
return ary;
}
private void printAry(int[] ary) {
System.out.println(Arrays.toString(ary));
}
private void swap(int[] iAry, int num1, int num2) {
int temp = iAry[num1];
iAry[num1] = iAry[num2];
iAry[num2] = temp;
}
@Test
public void sortTest() {
int[] iAry = createAry();
System.out.print("原始数组:");
printAry(iAry);
iAry = bubbleSort(iAry);
System.out.print("冒泡排序后的数组:");
printAry(iAry);
iAry = selectSort(iAry);
System.out.print("选择排序后的数组:");
printAry(iAry);
iAry = insertSort(iAry);
System.out.print("插入排序后的数组:");
printAry(iAry);