2012-06-22 111 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)