创建一个线程不起作用

时间:2015-12-07 09:11:03

标签: java multithreading

我正在尝试将线程实现到我正在处理的项目中,我不确定我哪里出错了。     包项目;

public class Launch{
    public static void main(String[] args) {
    Threads thread = new Threads();
    thread.start();
    }
}

class Threads implements Runnable{
static FruitSpawn spawn = new FruitSpawn();
    public void run(){
        spawn.spawnFruit();
    }
}

该程序要求我在Threads中创建一个名为start()的方法,而不是声明该线程。在创建线程时我哪里出错了?我在Java工作谢谢。

6 个答案:

答案 0 :(得分:2)

Threads正在实施Runnable而不是Thread,因此您无法在其上调用start()

执行:

Thread  t =new Thread(new Threads());
t.start();

答案 1 :(得分:1)

您创建了一个Thread,让您的Runnable运行,然后启动它。

class Threads implements Runnable {

    static FruitSpawn spawn = new FruitSpawn();

    public void run() {
        spawn.spawnFruit();
    }
}

public void test() {
    Threads spawner = new Threads();
    Thread t = new Thread(spawner);
    t.start();
}

答案 2 :(得分:0)

你可以做一些事情:

if (!s_server.listen(...))

Threads thread = new Threads(this); thread.start(); 创建一个新线程并拥有自己的执行场景。 thread.start()调用run方法asyc。当进入运行状态时。

答案 3 :(得分:0)

初始化时必须将Runnable传递给Thread类。

public class Launch{
    public static void main(String[] args) {
    Runnable runabl = new Threads(); 
    Threads thread = new Threads(runabl);
    thread.start();
    }
}

class Threads implements Runnable{
static FruitSpawn spawn = new FruitSpawn();
    public void run(){
        spawn.spawnFruit();
    }
}

答案 4 :(得分:0)

Threads正在实现Runnable接口,而不是扩展Thread类。所以,要么你应该 (a)让Threads类实现Runnable并使用 new Thread(new Threads())。start();

(b)增强Threads类以扩展Thread类,而不是实现Runnable接口。

答案 5 :(得分:0)

主要说Thread Class has 4-flavour Constructor 1. Thread(), 2. Thread(String threadName), 3. Thread(Runnable target), 4. Thread(Runnable target, String threadName). 同样,

Threads class which implements Runnable Interface.

现在你有Threads class called Runnable type Object

3rd flavor of Thread Class constructor.的对象。

现在你必须将那个Threads类Object传递给public class Launch{ public static void main(String[] args) { Threads runnableObject= new Threads(); Thread t = new Thread(runnableObject); // among of above listed 3rd flavor of Thread class constructor. t.start(); // start thread which will call run() of Threads Class. }

在代码中进行以下更改并享受!!

    "fnServerData" : function( sSource, aoData,fnCallback) {

      $.ajax({
                 "dataType" : 'json',
                 "type" : "GET",
                 "url" : sSource,
                 "data" : aoData,
                 "success" : fnCallback
            })
            .done(function(resp){
               alertFunction();
             })
            .fail(function(resp){
               alert("server error");
             });
};

}