xiac
xiac

Reputation: 77

Multithread warning in android

I have a problem with multithread. Warning is: "The method start() is undefined for the type MenuThread". What should I do

public void run() {
   if (whichMethodToCall == 1) {

   }
   else if (whichMethodToCall == 2) {

   }
}

Upvotes: 2

Views: 100

Answers (3)

Ravindra babu
Ravindra babu

Reputation: 38940

Problematic code:

MenuThread thread = new MenuThread(i);

Above line create MenuThread which implements Runnable interface. Still it's not a thread and hence

thread.start(); is illegal.

Right way to create Thread from Runnable instance

MenuThread thread = new MenuThread(i);
(new Thread(thread)).start();

You can create threads in two different ways. Have a look at oracle documentation about thread creation

An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:

  1. Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor

    public class HelloRunnable implements Runnable {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }
    
        public static void main(String args[]) {
            (new Thread(new HelloRunnable())).start();
        }
    }
    
  2. Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run

    public class HelloThread extends Thread {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }
    
        public static void main(String args[]) {
            (new HelloThread()).start();
        }
    
    }
    

Upvotes: 0

blafasel
blafasel

Reputation: 1121

Use new Thread(thread).start().

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157457

MenuThread is implementing the Runnable interface. It is not a thread. If you it to run on a different thread pass an instance of MyThread to a Thread object

 Thread thread = new Thread(new MenuThread(i));
 thread.start();

Upvotes: 4

Related Questions