【问题标题】:JAVA: How to start several threads in 1 class [closed]JAVA:如何在 1 个类中启动多个线程 [关闭]
【发布时间】:2013-07-03 11:04:35
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你能解释一下为什么你要启动许多听起来没有任何目的的线程吗?
  • 我们启动一个新线程来做一个逻辑。如果你需要做几个不相关的逻辑,你应该实现几个线程
  • 这甚至不会编译...你不能在静态方法中使用'this'

标签: java multithreading


【解决方案1】:

这段代码创建并启动了四个线程:

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();
    }
}

【讨论】:

  • 您不应该为每个Thread 使用不同的MyClass 实例吗?
  • 要在所有线程之间进行同步,所有线程必须属于同一个对象。如果您使用不同的对象创建线程,那么它们将不会同步。
  • 您可以使用相同的实例。但是如果你从多个线程修改这个实例的字段,你应该小心
  • @IvanM 这就是我提到它的原因,但要进行一些同步这是有道理的。
【解决方案2】:

假设你的线程类如下。

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(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2020-09-12
    • 2016-09-18
    • 1970-01-01
    相关资源
    最近更新 更多