版主,能帮我吗?

songnuan 2000-08-31 04:01:00
我有一个线程的程序Test.java如下:


class Test{
public static void main(String[] args){
Thread foo=new MyThread("Foo");
foo.setPriority(Thread.MIN_PRIORITY);
foo.start();
}
}
class MyThread extends Thread{
String mess;
MyThread (String mess){
this.mess=mess;
}
public void run(){
int i=0;
while(i<20){
try{
sleep(500);
System.out.println(mess+" "+getPriority());
System.out.println(i);
i++;
}
catch(InterruptedException e){}
}
}
}
此线程每0.5秒启动一下,我现在想将此线程作为一个事件源,自己做一个
监听器,当线程的状态改变时,监听器监听出变化,用来做出反应,请问
如何实现,本人对jdk1.1的委托机制了解。(最好有一个例子!)

谢谢!
...全文
153 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jackzhu 2000-09-06
  • 打赏
  • 举报
回复
定义你的事件,传递你需要的信息
public class YourEvent extends java.awt.AWTEvent
{
}
定义听众接口
public interface YourListener extends java.util.EventListener
{
public void stateChanged(YourEvent event);
}
类MyThread做如下修改
class MyThread extends Thread{
private Vector listeners;
public void addEventListener(YourListener listener)
{
if(!listeners.contains(listener))
{
listeners.addElement(listener);
}
}
private void notifyListeners()
{
Vector copyOfListeners = (Vector)(listeners.clone());
YourEvent event = new YourEvent(this);
Enumeration enum = copyOfListeners.elements();
while(enum.hasMoreElements())
{
YourListener listener = (YourListener)enum.nextElement();
listener.stateChangend(event);
}
}
public void run(){
int i=0;
while(i<20){
try{
sleep(500);
System.out.println(mess+" "+getPriority());
System.out.println(i);
i++;
notifyListeners();
}
catch(InterruptedException e){}
}
}
需要得到时钟消息的类实现YourListener即可
在main()中调用addListener(),增加希望监听的类

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧