2016-03-28 52 views
2

我遇到了多线程问题。警告是:“类型MenuThread的方法start()未定义”。我该怎么办Android中的多线程警告

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

    } 
    else if (whichMethodToCall == 2) { 

    } 
} 
+0

定义的run方法? –

+0

@blahfunk run方法是在MenuThread类中定义的,但其他类包含上面的代码,并没有看到启动方法。我应该怎么做 – xiac

+1

发布定义您的MenuThread类的代码,请 –

回答

4

MenuThread正在实现Runnable接口。这不是一个线程。如果它在不同的线程运行通过MyThread的实例给Thread对象

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

使用new Thread(thread).start()

0

问题的代码:

MenuThread thread = new MenuThread(i); 

上面一行创建MenuThread它实现Runnable接口。但它不是一个线程,因此

thread.start();是非法的。

权的方式从Runnable实例创建线程

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

您可以通过两种不同的方式创建线程。看看有关的oracle文档thread creation

创建Thread实例的应用程序必须提供将在该线程中运行的代码。有两种方法可以做到这一点:

  1. Provide a Runnable object.Runnable接口定义了一个方法,运行,意味着包含线程执行的代码。 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。 Thread类本身实现Runnable,尽管它的run方法什么也不做。应用程序可以继承Thread,提供它自己的实现运行

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