Search code examples
javamultithreadingclassoopthread-sleep

How to Multithread when already extending a class


I have a Java class which already extends the Java default UnicastRemoteObject:

public class ApplicationServerImpl extends UnicastRemoteObject implements ApplicationServer

I wish to create a thread within this class to perform a check periodically using thread.sleep - could someone please show me how this is possible if I am already extending a default Java class.


Solution

  • I'd take a look at some tutorials for threads.

    http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

    The tutorial shows you that you can fork a thread by implementing Runnable:

    public class ApplicationServerImpl extends UnicastRemoteObject
        implements ApplicationServer, Runnable {
        ...
    

    Then you can fork the thread like:

    new Thread(new ApplicationServerImpl()).start();
    

    Implementing Runnable is better because you can extend other classes.

    You also should look into using the ExecutorService classes which take care of much of the thread work from you:

    http://docs.oracle.com/javase/tutorial/essential/concurrency/exinter.html