Java - 如何为多个线程同步运行函数

标签 java multithreading

我必须为所有三个 使用名为 changeCaseRunnable 类的三个实例,并且仅使用一个 Server 类的实例ChangeCase 实例。流程执行需要连续运行,这就是为什么我在重写的 run 方法中使用了 while (true) 。每个线程的process方法执行是重叠的。我该如何解决这个问题?

我的代码:

package uppercase;

import java.util.Scanner;

class Server {

    void process(String threadName) {

        System.out.println("You are inside the Server " +threadName);

        System.out.println("Enter your sentence");
        Scanner sc1 = new Scanner(System.in);
        String input = sc1.nextLine();

        System.out.println("Press 1 to convert to Uppercase or Press 2 to convert to Lowercase");
        Scanner sc2 = new Scanner(System.in);
        int num = sc2.nextInt();

        switch (num) {
            case 1:
                changetoUpperCase(input);
                break;
            case 2:
                changetoLowerCase(input);
                break;
            default:
                System.out.println("Invalid number given\n\n");
                break;
        }
    }

    void changetoUpperCase(String msg) {

        printMessage(msg.toUpperCase());
    }

    void changetoLowerCase(String msg) {

        printMessage(msg.toLowerCase());
    }

    void printMessage(String msg) {

        System.out.println("[ " +msg+ " ]\n\n");

        try {
            Thread.sleep(1000);
        }catch (Exception e) {
           System.out.println(e.getMessage());
        }
    }
}

class changeCase implements Runnable {

    String threadName;
    Server target;
    Thread t;

    public changeCase(Server c, String s) {

        this.threadName = s;
        this.target = c;
    }

    @Override
    synchronized public void run() {

        while(true) {

            target.process(threadName);
        }

        //target.process(threadName);
    }

}

public class UpperCase {

    public static void main(String[] args) {

        Server s1 = new Server();

        Thread t1 = new Thread(new changeCase(s1, "Thread1"));
        Thread t2 = new Thread(new changeCase(s1, "Thread2"));
        Thread t3 = new Thread(new changeCase(s1, "Thread3"));

        t1.start();
        t2.start();
        t3.start();
    }

}

我需要的输出:

run:
You are inside the Server Thread1
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
1
[ HELLO WORLD ]


You are inside the Server Thread3
Enter your sentence
HELLO WORLD
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
2
[ hello world ]


You are inside the Server Thread2
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
4
Invalid number given


You are inside the Server Thread3
Enter your sentence

我得到的输出:

run:
You are inside the Server Thread1
Enter your sentence
You are inside the Server Thread2
Enter your sentence
You are inside the Server Thread3
Enter your sentence

最佳答案

可以使用计数器让线程一个接一个地执行。

class Server {
int threadCount = 3;
volatile int i = 1;

synchronized void process(String threadName) {
    int thread = Integer.parseInt(threadName.substring(threadName.length() - 1));
    if (thread % threadCount != i) {
        return;
    }
    i = i == threadCount - 1 ? 0 : i + 1;

    System.out.println("You are inside the Server " + threadName);

    System.out.println("Enter your sentence");
    Scanner sc1 = new Scanner(System.in);
    String input = sc1.nextLine();
...

关于Java - 如何为多个线程同步运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62127665/

相关文章:

java - 在iReport表达式中调用Java API

multithreading - ThreadPoolExecutor 与 threading.Thread

java - 无法使用 Poison Pill 停止生产者/消费者线程

java - getElementById 为 java 中的 xml 文档返回 null

java - 如何从 loadContent() 将 html 和 javascript 加载到 webengine 中?

java - JAXB 内容未实例化

java - 指定任务可执行位置 "C:\Program Files (x86)\Java\jdk1.7.0_71\\bin\javac.exe"无效

c# - 多线程服务器中的 Monitor.Wait/Pulse 竞争条件

java - CompletableFuture.thenAccept 确实可以阻塞

java - 客户端加锁是否违反了同步策略的封装?