线程的统制与监听
线程的控制与监听
--------续多线程小结
线程的创建主要有两种方式:使用 Thread 类和 Runable 接口。在使用 Runable 接口时需要建立一个 Thread 实例。因此,无论是通过 Thread 类还是 Runable 接口建立线程,都必须要建立 Thread 类或者它的子类实例。
线程的控制
通过用 while 判断循环是否执行,并通过自定义的方法实现线程的控制
while (! isStop ) {
while (! isPause ) {
}
}
/**
* 定义一个暂停线程的方法
*/
public static void pauseThread() {
isPause = true ;
}
/**
* 继续线程的方法
*/
public static void continueThread(){
isPause = false ;
}
/**
* 停止一个线程的方法
*/
public static void stopThread(){
isPause = true ;
isStop = true ;
}
线程的监听
为了能够控制多线程中个线程的具体情况,就需要对各个线程的执行进行监听,这可以通过创建一个监听线程来实现实时监控其他线程的目的;
/**
* 创建一个监听线程
*
* @author Administrator
*
*/
public class Listener extends Thread {
private ArrayList<Ball> list ;
int temp ;
int temp1 ;
public Listener(ArrayList<Ball> list) {
this . list = list;
}
public void run() {
while ( true ) {
for ( int i = 0; i < list .size() - 1; i++) {
for ( int j = i + 1; j < list .size(); j++) {
Ball b = list .get(i);
Ball b1 = list .get(j);
if (Math.sqrt ((b. X0 - b1. X0 ) * (b. X0 - b1. X0 )
+ (b. Y0 - b1. Y0 ) * (b. Y0 - b1. Y0 )) <= 40) {
temp = b. x ;
b. x = b1. x ;
b1. x = temp ;
temp1 = b. y ;
b. y = b1. y ;
b1. y = temp1 ;
}
}
}
try {
Thread.sleep (1);
} catch (Exception ef) {
ef.printStackTrace();
}
}
}
}