Home >Java >javaTutorial >How to use Thread class to create threads in Java?

How to use Thread class to create threads in Java?

王林
王林forward
2023-05-07 09:04:071217browse

There are two ways to create a thread in Java: using the Thread class and using the Runnable interface. When using the Runnable interface, you need to create a Thread instance. Therefore, whether you create a thread through the Thread class or the Runnable interface, you must create an instance of the Thread class or its subclass. The constructor of the Thread class has been overloaded eight times. The constructor is as follows:

public Thread( );  public Thread(Runnable target);  public Thread(String name);  public Thread(Runnable target, String name);  public Thread(ThreadGroup group, Runnable target);  public Thread(ThreadGroup group, String name);  public Thread(ThreadGroup group, Runnable target, String name);  public Thread(ThreadGroup group, Runnable target, String name, long stackSize);

Runnable target

An instance of a class that implements the Runnable interface. It should be noted that the Thread class also implements the Runnable interface, therefore, instances of classes inherited from the Thread class can also be passed into this constructor as targets.

String name

The name of the thread. This name can be set through the setName method of the Thread class after creating a Thread instance. If the thread name is not set, the thread uses the default thread name: Thread-N. N is the order in which the thread is created and is a non-repeating positive integer.

ThreadGroup group

The thread group to which the currently created thread belongs. If no thread group is specified, all threads are added to a default thread group. Details about thread groups will be discussed in detail in later chapters.

long stackSize

The size of the thread stack. This value is generally an integer multiple of the CPU page. For example, the page size of x86 is 4KB. Under the x86 platform, the default thread stack size is 12KB.

An ordinary Java class can become a thread class as long as it inherits from the Thread class. And the thread code can be executed through the start method of the Thread class. Although subclasses of the Thread class can be instantiated directly, the run method of the Thread class must be overridden in the subclass to actually run the thread's code. The following code gives an example of using the Thread class to create a thread:

package mythread;      public class Thread1 extends Thread    {        public void run()        {            System.out.println(this.getName());        }        public static void main(String[] args)        {            System.out.println(Thread.currentThread().getName());            Thread1 thread1 = new Thread1();            Thread1 thread2 = new Thread1 ();            thread1.start();            thread2.start();        }    }

The above code creates two threads: thread1 and thread2. Lines 005 to 008 in the above code are the run method of the Thread1 class. When the start method is called on lines 014 and 015, the system automatically calls the run method. In line 007, this.getName() is used to output the name of the current thread. Since the thread name is not specified when the thread is created, the thread name output is the system's default value, which is in the form of Thread-n. The thread name of the main thread is output on line 011.

The running results of the above code are as follows:

main
Thread-0
Thread-1

As can be seen from the above output results, *** The main line output is the name of the main thread. The following Thread-1 and Thread-2 are the output results of thread1 and thread2 respectively.

Note: Any Java program must have a main thread. Generally, the name of this main thread is main. Only by creating additional threads in the program can it be considered a true multi-threaded program. In other words, a multi-threaded program must have more than one thread.

The Thread class has an overloaded constructor to set the thread name. In addition to using the constructor method to set the thread name when creating a thread, you can also use the setName method of the Thread class to modify the thread name. To set the thread name through the constructor of the Thread class, you must use the public Thread(String name) constructor of the Thread class in the subclass of Thread. Therefore, you must also add a thread for passing in the subclass of Thread. Name constructor. The following code gives an example of setting the thread name:

package mythread;   public class Thread2 extends Thread  {      private String who;       public void run()      {          System.out.println(who + ":" + this.getName());      }      public Thread2(String who)      {          super();          this.who = who;      }      public Thread2(String who, String name)      {          super(name);          this.who = who;      }      public static void main(String[] args)      {          Thread2 thread1 = new Thread2 ("thread1", "MyThread1");          Thread2 thread2 = new Thread2 ("thread2");          Thread2 thread3 = new Thread2 ("thread3");          thread2.setName("MyThread2");          thread1.start();          thread2.start();          thread3.start();      }

There are two constructors in the class:

Line 011: public sample2_2(String who)

This constructor has one parameter: who. This parameter is used to identify the currently created thread. Thread's default constructor public Thread() is still called in this constructor.

Line 016: public sample2_2(String who, String name)

The who in this constructor has the same meaning as the who in the first constructor, and the name parameter is the thread's name. In this constructor, the public Thread(String name) constructor of the Thread class is called, which is super(name) on line 018.

Three threads are established in the main method: thread1, thread2 and thread3. Among them, thread1 sets the thread name through the construction method, thread2 modifies the thread name through the setName method, and thread3 does not set the thread name.

The running results are as follows:

thread1:MyThread1
thread2:MyThread2
thread3:Thread-1

As can be seen from the above output results, thread1 and The thread names of thread2 have been modified, but the thread name of thread3 is still the default value: Thread-1. The reason why the thread name of thread3 is not Thread-2 but Thread-1 is because the name of thread2 has been specified in line 026. Therefore, when thread3 is started, the thread name of thread3 is set to Thread-1. So you will get the above output.

Note: You can use setName to set the thread name before and after calling the start method. However, using setName to modify the thread name after calling the start method will cause uncertainty, which means that it may not be until the run method is executed. setName will be executed. If you want to use the thread name in the run method, there will be a phenomenon that although the setName method is called, the thread name is not modified.

The start method of the Thread class cannot be called multiple times. For example, the thread1.start() method cannot be called twice. Otherwise an IllegalThreadStateException will be thrown.

The above is the detailed content of How to use Thread class to create threads in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete