2012-06-22 113 views
2

我遇到了处理线程完成的类的问题。它可以通知其他线程,因为第二个线程可以启动。这是我的项目结构:线程监听器通知

MainClass.java

public class MainClass implements ThreadCompleteListener { 

public void main(String[] args) throws InterruptedException { 

    NotifyingThread test = new Thread1(); 
    test.addListener((ThreadCompleteListener) this); 
    test.start();   

} 

@Override 
public void notifyOfThreadComplete(Thread thread) { 
    // TODO Auto-generated method stub 

} 

} 

类 - Thread1.java

public class Thread1 extends NotifyingThread { 

@Override 
public void doRun() { 
    try { 
     metoda(); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

public static synchronized void metoda() throws InterruptedException { 
    for(int i = 0; i <= 3; i++) { 
     Thread.sleep(500); 
     System.out.println("method in Thread1"); 
    } 
} 

public void notifyOfThreadComplete(Thread thread) { 
    // TODO Auto-generated method stub 

} 
} 

NotifyingThread.java

import java.util.Set; 
import java.util.concurrent.CopyOnWriteArraySet; 

public abstract class NotifyingThread extends Thread { 
    private final Set<ThreadCompleteListener> listeners = new CopyOnWriteArraySet<ThreadCompleteListener>(); 
    public final void addListener(final ThreadCompleteListener listener) { 
    listeners.add(listener); 
    } 

    public final void removeListener(final ThreadCompleteListener listener) { 
    listeners.remove(listener); 
    } 

    private final void notifyListeners() { 
    for (ThreadCompleteListener listener : listeners) { 
     listener.notifyOfThreadComplete(this); 
    } 
    } 

    @Override 
    public final void run() { 
    try { 
     doRun(); 
    } finally { 
     notifyListeners(); 
    } 
    } 

    public abstract void doRun(); 
} 

我面对ThreadCompleteListener.java

public interface ThreadCompleteListener { 
void notifyOfThreadComplete(final Thread thread); 
} 

问题是,当我执行MainClass我得到这样的错误:致命异常发生。程序将退出,并在控制台显示:

java.lang.NoSuchMethodError:线程“main”主 异常

任何人都可以帮得到这在一个工作和平或者告诉什么,我在做什么错码?

非常感谢您的任何建议!

+0

notifyOfThreadComp lete是空的。这不是错误的原因,但它不会像你期望的那样工作。 – Alex

回答

7

更换公共无效的主要

公共static无效的主要

+0

当我用public static void main替​​换public void main时,我无法使用test.addListener((ThreadCompleteListener)this);因为我发现它不能用于静态对话 –

+0

是的,我想通了......你对Google搜索框的建议是如此的有用......它是一个这样的扩展工具不是吗?! –

+0

@MisterS当然你会得到一个错误!你需要用'new MainClass()'替换'this' –

2

我想你应该更换:

public void main(String[] args)