Home > Net >  Thread declaration Java
Thread declaration Java

Time:06-24

What is the meaning of Thread thread1 =new Thread(m1);? I don't understand the m1 inside the new Thread(m1).

class Test implements Runnable{  
    public void run(){  
        System.out.println("thread is running...");  
    }  
 
    public static void main(String args[]){  
        Test m1=new Test();  
        Thread thread1 =new Thread(m1);  
        thread1.start();  
    }  
}  

CodePudding user response:

m1 is the Runnable instance to be executed by the Thread.

Here what the documentation says:

public Thread(Runnable target)

Allocates a new Thread object. This constructor has the same effect as Thread (null, target, gname), where gname is a newly generated name. Automatically generated names are of the form "Thread-" n, where n is an integer.

Parameters: target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.

CodePudding user response:

The constructor of Thread takes a Runnable as parameter. Test is a implementation of Runnable.

Once you call thread1.start() the thread will do what ever you tell it to do in the Method public void run() in the class Test.

  • Related