How to pass parameter to an already running thread in java?

后端 未结 4 1157
独厮守ぢ
独厮守ぢ 2021-01-02 18:49

How to pass parameter to an already running thread in java -- not in the constructor, & probably without using wait() (possible ??)

Something similar to a comme

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 19:19

    What about such way:

        class TestRun implements Runnable
        {
            private int testInt = -1;
    
            public void setInt(int i)
            {
                this.testInt = i;
            }
    
            @Override
            public void run()
            {
                while (!isFinishing())
                {
                    System.out.println("Working thread, int : " + testInt);
                    try
                    {
                        Thread.sleep(2500);
                    }
                    catch (InterruptedException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    

    .....

            TestRun first = new TestRun();
            TestRun second = new TestRun();
            (new Thread(first)).start();
            (new Thread(second)).start();
            try
            {
                Thread.sleep(5000);
            }
            catch (InterruptedException e)
            {
            }
            first.setInt(101);
            second.setInt(102);
    

提交回复
热议问题