An object can create multiple threads in Java

I am a novice in multithreading. I wrote the following code during practice I want to call the createthreaded method to create a new thread I call evrytime However, using the code given below, I will run the same thread repeatedly every time I call the createthread method Can I create a new thread with the same object? Obviously not. I just want to make sure if there is a way I don't know

public class ThreadStartRunnable implements Runnable {

    private Thread t;
    /*
     ThreadStartRunnable(String name) {
         t = new Thread(this,name);
        t.start();
        }
     */
       private Thread createThread(String name){

         t = new Thread(this,name);
         t.start();
         return t;
     }

    /**
     * @Override run
     * 
     */
    public void run() {

        for(int i=0;i<=5;i++)
        {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("The current Thread is " + t.getName() + " and thread ID is " + t.getId());
        }
    }
    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args)  {
        // TODO Auto-generated method stub

        Thread t = Thread.currentThread();
        //new ThreadStartRunnable("User 1");
        //new ThreadStartRunnable("User 2");
        //ThreadStartRunnable c = new ThreadStartRunnable();
        ThreadStartRunnable t1 = new ThreadStartRunnable();

        t1.createThread("Child 1");
        t1.createThread("Child 2");

        for(int i=0;i<=5;i++)
        {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("The cirrent Thread is " + t.getName()+ " and thread ID is " + t.getId());
        }




    }

}

Solution

Change the code in the run method to display the name of the current thread:

System.out.println("The current Thread is " + Thread.currentThread().getName() + " and thread ID is " + Thread.currentThread().getId());

The instance variable t is overwritten every time a new thread is created, so it is not safe to use it to track the thread name and ID

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>