Mister S
Mister S

Reputation: 223

Thread listener notification

I'm having a problem with class which handles thread complete. It schould notify other threads that are fineshed so the second one can start. This is my project structure:

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

}   

}

Class - 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);
}

Problem which I face is that when I execute MainClass I'm getting an error like: Fatal exception occured. Program will exit and in console appears:

java.lang.NoSuchMethodError: main Exception in thread "main"

Could anyone help to get this in one working peace or tell what I'm doing wrong in the code?

Many thanks for any advice!

Upvotes: 2

Views: 5470

Answers (2)

DP Greveling
DP Greveling

Reputation: 409

I think you should replace:

public void main(String[] args)

for

public static void main(String[] args)

Upvotes: 2

Adel Boutros
Adel Boutros

Reputation: 10295

replace public void main

with public static void main

Upvotes: 7

Related Questions