【问题标题】:Running multiple functions of Runnable subclass (not only run())运行多个Runnable子类的函数(不仅仅是run())
【发布时间】:2014-05-11 22:09:37
【问题描述】:

是否可以线程运行Runnable子类的其他功能?

例如:

public class MyRunnable implements Runnable
{

@Override
public void run()
{
    for(int i = 0; i < 5; i++)
        System.out.println("\t\t" + i);
}

public void somethingElse(int amount)
{
    String tabs = "";
    for(int i = 0; i < amount; i++)
        tabs += "\t";

    for(int i = 0; i < 10; i++)
        System.out.println(tabs + i);
}

我可以在另一个线程(主线程除外)中运行 somethingElse() 和其他类似的函数吗?

我试过了:

 Thread thread = new Thread("New Thread") {
        public void run(){  
            MyRunnable x = new MyRunnable();
            x.somethingElse(1);
        }
    }; 

    Thread threadTwo = new Thread("New Thread") {
        public void run(){  
            MyRunnable x = new MyRunnable();
            x.somethingElse(2);
        }
    }; 

    thread.start();
    threadTwo.start();

但这是解决问题的正确方法吗?

【问题讨论】:

  • 您想在不同的威胁或相同的威胁(不是主要)中执行 run 和 somethingElse?
  • 在同一个线程中,而不是主线程。我正在实现一个数据库,我希望所有查询都在不同的线程中执行。

标签: java multithreading runnable


【解决方案1】:

正确的方法是创建两个不同的Runnable 对象,每个对象都有自己的run() 方法定义。

Thread t1 = new Thread(new Runnable1());
Thread t2 = new Thread(new Runnable2());
t1.start();
t2.start();

Java 只能通过在Runnable 实现或Thread 的子类上执行run() 方法来运行线程。

【讨论】:

    【解决方案2】:

    您的代码永远不会执行MyRunnable.run()。考虑一下这个

     MyRunnable r1 = new MyRunnable () ;
     r1.somethingElse(1); 
     Thread t1 = new Thread(r1,"Thread-R1") ;
     t2.start();
    

    在将线程实例提供给线程池之前,您可以调用线程实例中的任何方法(在您的情况下为 MyRunnable)。线程启动后,请考虑同步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 2020-11-07
      • 1970-01-01
      • 2011-02-18
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多