我试图了解如何在java中实现线程的方式。
现在我知道你可以使用接口(interface)runnable
和run方法来实现线程。
但是如果我想要同一个类有两个不同的线程,它们运行该类的不同方法怎么办?我只能重写 run 方法一次,所以我是否必须区分线程的名称,以便运行正确的方法?
public class PrintState {
private int state = 0;
public synchronized void printNewState() throws InterruptedException {
wait();
System.out.println(state);
}
public synchronized void setValue(int v) {
state = v;
notify();
System.out.println("value set");
}
}
我想要两个线程同时运行 printNewState()
和 setValue(12)
方法,每个线程都在不同的线程中。
如何实现 run()
方法和主方法中的线程才能实现此目的?
稍后的结果应该是:
值集
12
最佳答案
But what if I want to have two different threads of the same class, which run different methods of this class? I can only override the run method once, so do I have to make a distinction of for example the name of the thread in order to run the right method?
您需要区分执行线程和正在执行的代码。您可以使用一个 run()
来创建一个 Runnable
,并让 1000 个线程执行该 Runnable
。这意味着您有 1000 个线程执行相同的代码,尽管您可能只有一个 Runnable
实例来处理所有这些线程。
I want to have two Threads wich run the methods printNewState() and setValue(12) simultaneously, each one in a different thread.
你可以做这样的事情。请注意,我使用 lambda 来创建 Runnables
:
PrintState ps = new ...
Thread t1 = new Thread(ps::printNewState); //t1 will call printNewState
Thread t2 = new Thread(() -> ps.setValue(12)); //t2 will call setValue(12)
t1.start();
t2.start();
关于java - 如何在不同线程中运行同一个类的不同方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651619/