Home Java javaTutorial Create and start a Java thread

Create and start a Java thread

Feb 28, 2017 am 10:29 AM

Java thread is an object type similar to any other object. A thread is an instance of the java.lang.Thread class, or an instance of a subclass of this class. In addition to being an object type, Java threads can also execute code.

Create and start a thread

Create a thread like this:

Thread thread = new Thread();
Copy after login

To start a Java thread, you The start method needs to be called, like the following:

thread.start();
Copy after login

This example does not specify any code that the thread will execute. This thread will be stopped immediately after it is started.

There are two ways to specify what code this thread should execute. The first method is to create a subclass of thread and then override the run() method. The second method is to pass an object that implements the Runnable interface to the Thread constructor. Both methods are mentioned below.

Thread Subclass

The first way to specify what code a thread will run is to create a subclass of the thread and Override the run() method. This run() method is executed by this thread after you call the start() method. Here is an example:

public class MyThread extends Thread {

    public void run(){
       System.out.println("MyThread running");
    }
  }
Copy after login

To create and start the above thread, you can do as follows:

 MyThread myThread = new MyThread();
  myTread.start();
Copy after login


As soon as the thread is started, the start() method will return. It will not wait until the run() method ends. This run() method will be executed by different CPUs. When this run() method is executed, it will print out the text content "MyThread running".

You can also create an anonymous subclass of a thread as follows:

Thread thread = new Thread(){
    public void run(){
      System.out.println("Thread Running");
    }
  }

  thread.start();
Copy after login


The running results of this example will be the same as above.

Runnable interface implementation

The second way to specify what code a thread should run is by creating an implementation of the java.lang.Runnable interface of a class. This Runnable object can be executed by a thread.

Here is an example:

public class MyRunnable implements Runnable {

    public void run(){
       System.out.println("MyRunnable running");
    }
  }
Copy after login

In order for the run method to be executed by a thread, you need to pass a MyRunnable instance to the constructor of a thread. Here is an example:

Thread thread = new Thread(new MyRunnable());
   thread.start();
Copy after login

When this thread starts, it will call the run method of MyRunnable instead of executing its own run method. The above example will print the text "MyRunnable running".

You can also create an anonymous implementation like this:


Runnable myRunnable = new Runnable(){

     public void run(){
        System.out.println("Runnable running");
     }
   }

   Thread thread = new Thread(myRunnable);
   thread.start();
Copy after login


Inherit Thread or implement the interface?

There are no rules here as to which of the two methods is best. Both ways will work. However, for me personally, I prefer to implement the Runnable interface and manage instances of this implementation as a Thread instance. When there is a Runnable implementation that is executed by a thread pool, it is simple to queue Runnable instances until threads from the pool are free. This is a bit difficult to achieve using a Thread subclass.

Usually you not only need to implement Runnable, but also implement the subclass Thread. For example, if you create a Thread subclass you can execute more than one Runnable. This is a typical example of implementing a thread pool.

Common pitfall: calling run() instead of start()

When creating and starting a thread, a common mistake is to call Thread's run method replaces the start method, like the following:

Thread newThread = new Thread(MyRunnable());
  newThread.run();  //should be start();
Copy after login

First of all, you may not notice anything, because Runnable's run method will also execute as you expect. However, it will not be executed by the new thread you create. The run method of the thread that replaced the thread that created it is executed. In other words, the thread on which the above two lines of code execute. In order for the run method of the newly created thread instance to be called, you must call the start method.

Thread name

When you create a java thread, you can give it a name. This name helps you distinguish between different threads. For example, if multiple threads write this output, it can be seen which thread wrote which text. Here is an example:

Thread thread = new Thread("New Thread") {
      public void run(){
        System.out.println("run by: " + getName());
      }
   };


   thread.start();
   System.out.println(thread.getName());
Copy after login


Note the character channel parameter passed to the Thread constructor. This string is the name of the thread. This name can be obtained through Thread's getName method. When running a Runnable implementation, you can also pass a name. Like the following:

MyRunnable runnable = new MyRunnable();
   Thread thread = new Thread(runnable, "New Thread");

   thread.start();
   System.out.println(thread.getName());
Copy after login


However, be aware that because the MyRunnable class is not a subclass of the Thread class, it cannot access the getName() method of the thread that is executing it.

Thread.currentThread()

This method returns a reference to the Thread instance of the current thread being executed. This way you can access the Thread object of the thread that is executing the block of code. Here's an example:

Thread thread = Thread.currentThread();
Copy after login


Once you have a reference to a Thread object, you can call methods on it. For example, you can get the name of the thread executing:

String threadName = Thread.currentThread().getName();
Copy after login


Java Thread Instance

这里有一个小的例子。首先它打印出来了正在执行的main方法的线程的名字。这个线程是被JVM分配的。然后启动了10个线程,以及给予他们所有作为名称(“”+i)的一个数字。每一个线程然后打印出名字,以及停止执行。

public class ThreadExample {

  public static void main(String[] args){
    System.out.println(Thread.currentThread().getName());
    for(int i=0; i<10; i++){
      new Thread("" + i){
        public void run(){
          System.out.println("Thread: " + getName() + " running");
        }
      }.start();
    }
  }
}
Copy after login


注意,甚至如果线程是按顺序启动的(1,2,3等等)。他们可能也不会按顺序执行的,意味着线程1可能不是第一个打印出来的名字。这个就是为什么原则上线程是并行运行而不是顺序呢执行的原因了。这个JVM以及操作系统决定着线程执行的顺序。这个顺序每次在他们启动的时候都不会相同的。
以上就是创建以及启动一个Java线程的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve application startup error 0xc000012d problem How to solve application startup error 0xc000012d problem Jan 02, 2024 pm 12:53 PM

When a friend's computer is missing certain files, the application cannot start normally with error code 0xc000012d. In fact, it can be solved by re-downloading the files and installing them. The application cannot start normally 0xc000012d: 1. First, the user needs to download ".netframework". 2. Then find the download address and download it to your computer. 3. Then double-click on the desktop to start running. 4. After the installation is completed, return to the wrong program location and open the program again.

How to solve the computer prompt 'reboot and select proper boot device' How to solve the computer prompt 'reboot and select proper boot device' Jan 15, 2024 pm 02:00 PM

Reinstalling the system may not be a foolproof solution, but after reinstalling, I found that when the computer is turned on, it will display white text on a black background, and then give a prompt: rebootandselectproperbootdevice, what is going on? Such a prompt is usually caused by a boot error. In order to help everyone, the editor has brought you a solution. Computer use is becoming more and more popular, and computer failures are becoming more and more common. No, recently some users encountered a black screen when turning on the computer, and prompted Reboot and Select Proper Boot device, and the computer system could not start normally. What's going on? How to solve it? The user is confused. Next, the editor will follow

What should I do if wps cannot start the source application of this object? What should I do if wps cannot start the source application of this object? Mar 13, 2024 pm 09:13 PM

WPS is a very widely used office software, including documents, forms and PPT, and supports multi-terminal synchronization. If the prompt "The source application for this object cannot be launched" appears when editing wps, how to solve it? This problem may occur because you are trying to open a link or file, but its source application no longer exists or has been deleted. Here are some fixes: 1. Reinstall WPS software: Try reinstalling WPSOffice to fix the problem and make sure you are using the latest version. 2. Manually change the default program: Try to change the default program to WPS. You can right-click the file you want to open, select "Open with", and then

Effective solutions and techniques for Ubuntu startup black screen problem Effective solutions and techniques for Ubuntu startup black screen problem Dec 29, 2023 am 10:30 AM

Practical tips and methods to solve the black screen on Ubuntu startup Introduction: Ubuntu is a popular Linux operating system, but sometimes you may encounter a black screen problem during the startup process. This problem can be caused by a variety of reasons, such as graphics card driver issues, software conflicts, or system errors. This article will introduce some practical tips and methods to help solve the black screen problem at Ubuntu startup to ensure the stable operation of the system. 1. Update and reinstall the graphics card driver to enter recovery mode: press the Shift key during startup to enter

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

How to set the boot priority of Apple dual system How to set the boot priority of Apple dual system Feb 19, 2024 pm 06:49 PM

As technology continues to develop, the need to use different operating systems is becoming more and more common. For Apple users, sometimes you may need to install and use two different operating systems on one device, such as macOS and Windows. In this case, it is particularly important to set the startup sequence of the dual system. This article will introduce how to set up Apple devices to start the dual system first when turning on the device. First, we need to make sure that both operating systems have been successfully installed on the Apple device. You can use BootCamp this Apple

How to create pixel art in GIMP How to create pixel art in GIMP Feb 19, 2024 pm 03:24 PM

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

Which one to choose when starting wallpaperengine? Which one to choose when starting wallpaperengine? Mar 19, 2024 am 08:49 AM

When wallpaperengine starts, there are 4 different options. Many users don't know which one to choose when starting wallpaperengine. Generally, when wallpaperengine starts, choose the first one: start 32-bit. Which one to choose when starting wallpaperengine? Answer: Start 32-bit. 1. Generally, when wallpaperengine starts, select the first one: start 32-bit. 2. When wallpaperengine starts, there are 4 different options: start 32-bit; start 64-bit. 3. Start 32-bit: This is a generally recommended option and suitable for most users. 4. Start 64-bit: If the system supports 64-bit, you can choose this option

See all articles