java - 多线程 - 为所有变量请求一次输入 (Java)

标签 java multithreading

下面是多线程函数的代码和输出,其中有一个计数器以及加、减、乘和除函数。我正在使用 Eclipse。

每个数学函数有 4 个线程:

public class Maths {

    public static void main(String args[]){

        CalculationThread T1 = new CalculationThread("Addition");
        T1.start();

        CalculationThread T2 = new CalculationThread("Subtraction");
        T2.start();

        CalculationThread T3 = new CalculationThread("Multiplication");
        T3.start();

        CalculationThread T4 = new CalculationThread("Division");
        T4.start();
    }
}

class CalculationThread extends Thread{
    private Thread t;
    private String maths;
    private int count = 0;
    private int resultplus, resultminus, resulttimes, resultdivide = 0;

    CalculationThread(String answer){
        maths = answer;
    }

    public void start(){
        System.out.println("Starting calculation of " + maths + "\n");
        if(t == null){
            t = new Thread (this, maths);
            t.start();
        }
    }

这里是函数发生的地方,它将使用计数器作为 2 个数字来执行方程式。

    public void run(){
        try {
            for (int x=0; x<=3 ; x++){

                if(maths == "Addition"){
                System.out.println("Calculating: " + maths + " of " + count + 
                        " + "+ count + " = " + resultplus + "\n");
                Thread.sleep(3000);
                count++;
                resultplus = count + count;
                }

                else if(maths == "Subtraction"){
                    System.out.println("Calculating: " + maths + " of " + count + 
                            " - "+ count + " = " + resultminus + "\n");
                    Thread.sleep(3000);
                    count++;
                    resultminus = count - count;
                }

                else if(maths == "Multiplication"){
                    System.out.println("Calculating: " + maths + " of " + count + 
                            " * "+ count + " = " + resulttimes + "\n");
                    Thread.sleep(3000);
                    count++;
                    resulttimes = count * count;
                }

                else if(maths == "Division"){
                    System.out.println("Calculating: " + maths + " of " + count + 
                            " / "+ count + " = " + resultdivide + "\n");
                    Thread.sleep(3000);
                    count++;
                    resultdivide = count / count;
                }

            }

        }
            catch (InterruptedException e){
                System.out.println("Math function failed");
            }
                if(maths == "Addition"){
                System.out.println("Addition completed.");
                }
                else if(maths == "Subtraction"){
                    System.out.println("Subtraction completed.");
                }
                else if(maths == "Multiplication"){
                    System.out.println("Multiplication completed.");
                }
                else if(maths == "Division"){
                    System.out.println("Division completed.");
                }
    }
}

输出:

Starting calculation of Addition

Starting calculation of Subtraction

Calculating: Addition of 0 + 0 = 0

Starting calculation of Multiplication

Calculating: Subtraction of 0 - 0 = 0

Starting calculation of Division

Calculating: Multiplication of 0 * 0 = 0

Calculating: Division of 0 / 0 = 0

Calculating: Subtraction of 1 - 1 = 0

Calculating: Addition of 1 + 1 = 2

Calculating: Multiplication of 1 * 1 = 1

Calculating: Division of 1 / 1 = 1

Calculating: Addition of 2 + 2 = 4

Calculating: Subtraction of 2 - 2 = 0

Calculating: Division of 2 / 2 = 1

Calculating: Multiplication of 2 * 2 = 4

Calculating: Subtraction of 3 - 3 = 0

Calculating: Addition of 3 + 3 = 6

Calculating: Division of 3 / 3 = 1

Calculating: Multiplication of 3 * 3 = 9

Subtraction completed.
Addition completed.
Division completed.
Multiplication completed.

上面的代码可以同时完成所有 4 个函数,但是每当我尝试包含一个 JOptionPane 用于用户输入而不是自动计数器时,4 个线程中的每一个都会同时请求。因此,如果函数正在等待我输入 2 个数字,则它不会被算作多线程。我如何以及以什么方式包含用户输入,只需要用户在开始时输入,以便所有函数都可以使用这两个变量。

最佳答案

不知道我理解是否正确。

如果您只想阻止计算线程并等待初始用户输入,您可以使用信号量

等待用户输入的UI线程显示对话框,并通过设置许可/线程数来释放等待的计算线程。

这是一个示例(它还使用了更面向对象的方法)。为了简单起见,我跳过了乘法和除法任务

import java.util.concurrent.Semaphore;

import javax.swing.JOptionPane;

public class MathSample {

    // because updated / read from different threads mark as volatile 
    private volatile int a, b;

    // semaphore with no initial permits i.e.
    // the calculations will wait until permits are available.
    private Semaphore available = new Semaphore(0);

    private abstract class Task implements Runnable {

        public abstract void doCalculation();

        public abstract String getName();

        @Override
        public void run() {
            try {
                // wait until a permit becomes available
                available.acquire();
                // not sure what should happen here
                // wait again for user input? 
                for (int x = 0; x < 50; ++x) {
                    a = a + x;
                    doCalculation();
                }

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            System.out.println(String.format("Task %s completed.", getName()));
        }

    }


    private  class AdditionTask extends Task {

        public void doCalculation() {
            System.out.println(String.format("Calculating: Addition of + %d + %d = %d", a, b, a+b));
        }
        public String getName() {
            return "Addition";
        }
    }

    private  class SubstractionTask extends Task {
        public void doCalculation() {
            System.out.println(String.format("Calculating: Substraction of + %d - %d = %d", a, b, a-b));
        }

        public String getName() {
            return "Substraction";
        }
    }



    private void run() {
        new Thread(new AdditionTask()).start();
        new Thread(new SubstractionTask()).start();


        a = Integer.parseInt(JOptionPane.showInputDialog("First value"));
        b = Integer.parseInt(JOptionPane.showInputDialog("Second value"));
        available.release(2); // let the 2 calculation threads run

    }


    public static void main(String ...args) {
        new MathSample().run();

    }
}

正如您所看到的,您不必覆盖线程的 start 方法来运行不同的线程。

您的 CalculationThread 的 start 方法至少很奇怪,因为您覆盖了 Thread 类的 start 方法,并在其中创建了另一个您将 CalculationThread 作为 Runnable 传递的线程实例。

更容易/更好:

class Calculation implements Runnable {
   ...
   @override 
   public void run() {
      // the name you passed to the thread is your math 
      // lets get it from the currently running thread where it is stored.         
      final String math = Thread.currentThread().getName();
      ...
   }

}

// somewhere else 
new Thread(new CalculationThread, math).start(); 

关于java - 多线程 - 为所有变量请求一次输入 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642448/

相关文章:

java - Persistence.createEntityManagerFactory ("something")返回 null

java - 如何以更简单的方式从 XML 文件中获取单个属性

java - 多客户端java客户端服务器聊天

java - Spring Security 未应用于我的 URL

pthread_mutex_lock() 能否在 pthread_cond_wait() 解除阻塞之前解除阻塞?

java - 在 Runnable 线程中访问 Spring bean

c++ - 其他线程位置

java - 为什么我的实时结果没有在 main 中更新?

multithreading - 具有 CPU 绑定(bind)例程的多线程?

c# - 使用成员函数启动线程