-8

在java中启动单线程,类应该实现它的run方法

public class MyClass implements Runnable {
    run() {
        // some stuff
    }

    public static void main(String []args) {
        Thread myThread = new Thread(this);
        myThread.start();
    }
}

问题是如果我需要在课堂上启动几个不同的线程,我应该怎么做。我知道一种方法——为每个线程函数实现类,但我认为应该有更简单的方法。

4

2 回答 2

2

此代码创建并启动四个线程:

public class MyClass implements Runnable {
    run() {
        // some stuff
    }

    public static void main(String []args) {
        MyClass myClass = new MyClass();
        Thread t1 = new Thread(myClass);
        Thread t2 = new Thread(myClass);
        Thread t3 = new Thread(myClass);
        Thread t4 = new Thread(myClass);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
于 2013-07-05T11:04:54.180 回答
0

假设您的线程类如下。

public class MyClass implements Runnable{  
public MyClass(){}  
public void run(){  
// some operation here  
}  
}  

在您的 MainClass 中,您可以启动尽可能多的线程:

   MyClass obj1 = new MyClass();  
    MyClass obj2 = new MyClass();  
    Thread t1 = new Thread(obj1);  
    Thread t2 = new Thread(obj2);  
    t1.start();  
    t2.start(); 
于 2013-07-05T11:05:13.217 回答