【发布时间】: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