【问题标题】:calling method for my thread object i created but is not working. no errors我创建但不工作的线程对象的调用方法。没有错误
【发布时间】:2018-03-04 01:17:24
【问题描述】:

这是代码...

import java.util.Scanner;

class Draft extends Thread
{

    String name;
    static int counter;
    boolean islive; //...

//  the constructor
    public Draft(String name, int counter, boolean islive)
    {
        this.name = name;
        this.counter = counter;
        this.islive = islive;   //...
    }

    void stopTheThread()
    {
        this.islive = false;    //...
    }

    @Override
    public void run()
    {
        while(islive)   //...
        {
            counter++;
            try
            {
                sleep(913);
            }
            catch (InterruptedException e) { } 
        }
    }

//  the main function
    public static void main(String[] args)
    {
//      intializing two threads
        Draft Tone = new Draft("Tone", 13, true);
        Draft Ttwo = new Draft("Ttwo", 26, true);

        System.out.println("All Thread Started!");
        Tone.start();    Ttwo.start();

        Scanner scan = new Scanner(System.in);
        String go = "";

//      the while loop.......
        while(!go.toLowerCase().equals("exit")) {

            System.out.println();   //just a new line
            System.out.print("Command: ");
            go = scan.next();

            if(go.equals("1")) {
                System.out.print("Thread one "+ Tone.counter);
            }
            else if(go.equals("2")) {
                System.out.print("Thread wo: "+ Ttwo.counter);
            } 
            else if(go.equals("1Stop")) {
                Tone.stopTheThread();   //is not stoping
                System.out.print("Thread one Stopped"); //but printing
            } 
            else if(go.equals("2Stop")) {
                Ttwo.stopTheThread();   //is not stopping too
                System.out.print("Thread two Stopped"); //printing too
            }

        }//end of the while

    }//end of main

}   //end of Draft

我为我的 Draft 类扩展了 Thread 类。 在 run 方法中,线程主要在 isive 条件下的 while 循环上运行,该条件是一个布尔值。

我创建了一个方法 stopTheThreadisalive 设置为 false 并且 run 方法上的循环应该停止. 但实际上,当我在 ToneTtwo 的主要方法中调用它时,它并没有停止。两者都是在 main 方法上创建的两个线程对象。

检查所有条件。

我做错了什么?

【问题讨论】:

    标签: java multithreading methods constructor boolean


    【解决方案1】:

    看起来两个线程都在增加相同的 STATIC 计数器变量,所以它们都在运行并增加相同的变量。 我测试了代码并按预期工作,计数器会递增,直到我“停止”两个线程,如果您希望每个线程都增加自己的变量,您应该删除静态修饰符。

    【讨论】:

    • 但我创建了两个不同的对象。音调和Ttwo。并且 counter 对于每个对象应该是延迟的。那么为什么两个线程都会增加相同的计数器。我没明白。你能解释一下吗?
    • 为什么你在这里提到静态?如果我删除它的工作原理。为什么?
    • @Rabin:你怎么看,static 是什么意思?
    • @Rabin Static 表示无论创建多少个包含类(Draft)的实例,都会有一个共享的唯一实例,每个实例都将共享同一个静态对象(计数器)。跨度>
    • @DanielRodriguez 所以我的两个线程实例使用相同的计数器。这就是为什么当我停止一个线程时,计数器仍然由另一个线程增加,直到我也停止它。那是静态唯一的作用吗?为什么我们通常在主要方法中使用静态?你能解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多