2009年4月10日 天气:晴
Java多线程编程。
实现多线程的类要实现Runnable接口的void run()方法,或继承Thread类重写其中的run()方法。
驱动方法中先实例化一个类(实现接口或继承,重写run()方法的类),然后新建线程,将对象传进去。
然后start()。即可。
实例:Java演示选择排序。
Sorting类
package p9_6;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class Sorting implements Runnable
{
Comparable[] list;
JPanel panel;
public Sorting(Comparable[] eList, JPanel ePanel)
{
list=eList;
panel=ePanel;
}
public void run() //实现
{
int min;
Comparable temp;
for( int index=0; index<list.length-1; index++ )
{
min=index;
for(int scan=index+1; scan<list.length; scan++)
if(list[scan].compareTo(list[min])<0)
min=scan;
temp=list[min];
list[min]=list[index];
list[index]=temp;
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
Logger.getLogger(Sorting.class.getName()).log(Level.SEVERE, null, ex);
}
panel.repaint();
}
}
}
SortPanel类,JPanel的继承
package p9_6;
import javax.swing.*;
import java.awt.*;
import java.lang.Thread;
public class SortPanel extends JPanel{
final int BOTTOM=400;
final int LEFT=20;
final int WIDTH=20;
private int count;
private Integer[] arr;
public SortPanel(int eCount, Integer[] eArr)
{
count=eCount;
arr=new Integer[count];
for(int i=0; i<count; i++)
arr[i]=eArr[i];
Sorting sts=new Sorting(arr, this);
Thread thd=new Thread(sts);
thd.start();
}
public void paint(Graphics g)
{
super.paint(g);
Color[] cl={Color.RED, Color.GREEN, Color.CYAN, Color.MAGENTA, Color.BLACK, Color.BLUE, Color.ORANGE, Color.PINK};
int left=LEFT;
int top;
for( int i=0; i<count; i++)
{
g.setColor(cl[i]);
top=25*arr[i];
g.fillRect(left, BOTTOM-top, WIDTH, top);
g.setColor(Color.BLACK);
g.drawString(Integer.toString(i), left+WIDTH/4, BOTTOM+15);
left+=2*WIDTH;
}
}
}
驱动类Main
package p9_6;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame=new JFrame();
Integer[] arr={10, 3, 14, 1, 5, 2, 6, 12};
SortPanel panel=new SortPanel(8, arr);
frame.getContentPane().add(panel);
frame.setPreferredSize(new Dimension(500, 600));
frame.pack();
frame.setVisible(true);
}
}