java - 如何在不同线程中运行同一个类的不同方法?

标签 java multithreading synchronization

我试图了解如何在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/

相关文章:

java - 加载jar附带的JNA库

c++ - C++ 中带线程的时钟函数

c++ - 当调度策略为 SCHED_RR 时,pthread 临界区中运行时间峰值的原因可能是什么?

javascript - 主干(同步)更新事件

javascript - 在浏览器开发工具中检查 ajax 调用是同步还是异步

java - Spring-MVC : How to ensure multiple users will be able to call a method in sequence

java - Java程序无法编译: missing return statement

java - 在 createQuery 中使用 SELECT DISTINCT 返回列表值

尽管使用 CLASSPATH 环境变量,但仍出现 java.lang.ClassNotFoundException

c# - 从用户界面调用System.Threading.Thread时,锁将挂起。