繁体   English   中英

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

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

这是我的代码(类):

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);
                }
            }
        }
    }
}

这是我的主要课程:

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();
    }
}

我一次只需要1个线程,并且只需要一个唯一线程。 首先是a1,然后是a2,然后是a1和a2,但是现在,当我运行我的代码时,我得到的复制像是先启动a1然后启动a2,然后在3-4增量之后启动a1,然后再次启动a1,然后启动a2,然后再次启动a2。 我尝试了许多不同的操作,但由于我是新手,所以无法正常工作。

请帮忙

如果要使用布尔值切换标志,则必须多次检查它……就像这样:

(伪代码)

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;
    }
}

您可能需要检查其他条件。 例如,如果a1的迭代次数与a2不同。

我知道这不是完整的工作代码。 但是,由于这是一项任务,所以我只想给您一个提示,让您自己解决。

祝好运!

编辑:我不认为这是最好的解决方案,并且肯定不是唯一的解决方案。

那么,为什么要在这种情况下使用线程?

只需将线程的逻辑放在方法(或普通类)中,并在您的主线程中,只需循环即可调用该方法。

如果您真的想像在这里一样使用线程,则可以做很多事情:

方法1:首先,如果希望a1和a2继续运行,则应具有某种循环以使其一次又一次地运行。 第一种方法是在主线程中循环,然后在启动a1或a2之后添加a1.join()/ a2.join(),这样它将启动一个线程,等待其完成,然后启动下一个线程。

方法2:您可能在线程中具有循环,并且两个线程共享一个监视器/信号灯。 在循环中运行逻辑之前,请获取监视器,如下所示:

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

方法3:创建一个执行程序,而不是自己管理线程。 考虑为执行程序使用2元素块队列,并且可以使用1线程线程池执行程序。 因此,您的主循环将继续创建代表a1 / a2逻辑的Runnable,并提交给执行程序以execute Runnable。

我建议使用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();
    }
}

感谢Niraj Rathi

暂无
暂无

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

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