简体   繁体   English

在JAVA程序中一次只有1个线程

[英]only 1 Thread at a time in JAVA program

Here's my code (Class): 这是我的代码(类):

package table2thread;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Table2Thread extends Thread {

    private int j;
    private boolean flag;

    Table2Thread(int j0) {
        j = j0;
    }

    public void run() {

        if (Thread.currentThread().getName().equals("Thread1")) {
            for (int i = 1; i < 11; i++) {
                System.out.println(j + "*" + i + "=" + j * i);
                flag = true;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Table2Thread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else if (Thread.currentThread().getName().equals("Thread1") && flag == true) {
            for (int i = 1; i < 11; i++) {
                System.out.println(j + "*" + i + "=" + j * i);
                flag = false;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Table2Thread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

Here is my main class: 这是我的主要课程:

public class Main {
    public static void main(String[] args) {

        Table2Thread a1 =new Table2Thread(3);
        a1.setName("Thread1");
        a1.start();
        Table2Thread a2 =new Table2Thread(4);
        a2.setName("Thread2");
        a2.start();
    }
}

I need only 1 thread at a time and only unique one. 我一次只需要1个线程,并且只需要一个唯一线程。 First a1 then a2 then again a1 and a2, but right now when i run my code i get the duplication like first a1 starts then a2 then after 3-4 increments a1 starts and again a1 starts then a2 starts and again a2 starts. 首先是a1,然后是a2,然后是a1和a2,但是现在,当我运行我的代码时,我得到的复制像是先启动a1然后启动a2,然后在3-4增量之后启动a1,然后再次启动a1,然后启动a2,然后再次启动a2。 I tried many different things but as i am newbie i am unable to get it to work. 我尝试了许多不同的操作,但由于我是新手,所以无法正常工作。

PLEASE HELP 请帮忙

If you want to use a boolean toggle-flag you have to check it more than once ... like this: 如果要使用布尔值切换标志,则必须多次检查它……就像这样:

(Pseudo-Code) (伪代码)

public static volatile boolean toggle = true;

... ...

if( isThread1 )
{
    for( ... )
    {
        while( !toggle )
        {
            Thread.sleep(100);
        }
        // Do your stuff here
        toggle = false;
    }
}
else
{
    for( ... )
    {
        while( toggle )
        {
            Thread.sleep(100);
        }
        // Do you stuff here
        toggle = true;
    }
}

You may have to check for additional conditions. 您可能需要检查其他条件。 For example if a1 has a different number of iterations than a2. 例如,如果a1的迭代次数与a2不同。

I know this not complete working code. 我知道这不是完整的工作代码。 But since this is an assignment, I just wanted to give you a hint to work it out yourself. 但是,由于这是一项任务,所以我只想给您一个提示,让您自己解决。

Good luck! 祝好运!

Edit: I do not claim that this is the best solution and it sure isn't the only one. 编辑:我不认为这是最好的解决方案,并且肯定不是唯一的解决方案。

Why would you want to use threading in such case then? 那么,为什么要在这种情况下使用线程?

Simply put the logic of your thread in a method (or a plain class), and in your main, just loop to invoke that method. 只需将线程的逻辑放在方法(或普通类)中,并在您的主线程中,只需循环即可调用该方法。

If you really want to use thread like what you do here, there are lots of thing you can do: 如果您真的想像在这里一样使用线程,则可以做很多事情:

Method 1: First if you want a1 and a2 to keep running, you should have some kind of loop to keep them running again and again. 方法1:首先,如果希望a1和a2继续运行,则应具有某种循环以使其一次又一次地运行。 First way is have a loop in your main, and after starting a1 or a2, add a a1.join()/a2.join(), so that it will start a thread, wait until it finish, and then start the next one. 第一种方法是在主线程中循环,然后在启动a1或a2之后添加a1.join()/ a2.join(),这样它将启动一个线程,等待其完成,然后启动下一个线程。

Method 2: You may have the loop in the thread instead, and both thread share a monitor/semaphore. 方法2:您可能在线程中具有循环,并且两个线程共享一个监视器/信号灯。 Before running the logic in the loop, acquire the monitor, like this: 在循环中运行逻辑之前,请获取监视器,如下所示:

public void run() {
   while (running) {
      synchronized(sharedMonitor) {
          while (flag != thisThread) {
              sharedMonitor.wait();
          }
          //your actual logic here
          flag = nextThread;
          sharedMonitor.notifyAll();
      }
   }
}

Method 3: Instead of managing the thread yourselves, create a Executor. 方法3:创建一个执行程序,而不是自己管理线程。 Consider using a 2 element block queue for the executor, and you may use a 1-thread Thread Pool Executor. 考虑为执行程序使用2元素块队列,并且可以使用1线程线程池执行程序。 So your main loop will keep creating Runnable which represent the logic of your a1/a2, and submit to the executor to execute the Runnable. 因此,您的主循环将继续创建代表a1 / a2逻辑的Runnable,并提交给执行程序以execute Runnable。

I suggest to use Thread::Join method. 我建议使用Thread :: Join方法。

public class Main {
    public static void main(String[] args) {

        Table2Thread a1 =new Table2Thread(3);
        a1.setName("Thread1");
        a1.start();
        a1.join();
        Table2Thread a2 =new Table2Thread(4);
        a2.setName("Thread2");
        a2.start();
    }
}

Thanks Niraj Rathi 感谢Niraj Rathi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM