Table of Contents
Initial exploration of Thread
Preface
Create thread
Inherit Thread
Implements the Runnable interface
The creation method
Commonly used methods
Home Java javaTutorial The definition and common methods of Thread

The definition and common methods of Thread

Jun 21, 2017 am 09:36 AM
thread Preliminary exploration

Initial exploration of Thread

Preface

In the past, everyone wrote single-threaded programs, all calling methods in the main function. You can clearly see that its efficiency is It is particularly low, just like using a single thread to crawl a website in Python, it can be said that it can make you vomit blood because the amount of data is too large. Today we will take a look at the learning of concurrent programming and multi-threading in Java

Create thread

There are many ways to create a thread, such as inheriting the Thread class and implementing the Runnable interface... Let's take a detailed look at the creation method.

Inherit Thread

Why inheriting Thread can directly call the start() method to start the thread, because start() itself is a method of Thread, that is, it inherits the start() method of Thread, so the object of this class can call start() to start the thread

//继承Threadpublic class MyThread extends Thread {    public void run() {for (int i = 0; i < 10; i++) {
            System.out.println(this.getName()+"正在跑");
        }
    }
}public class Test{public static void main(String[] args)
    {
        Mythread t1=new MyThread();   //创建对象t1.start();     //启动线程}
}
Copy after login

Note: Inherit the creation method of the Thread class. An object can only create one thread, and multiple threads cannot share one object. Only one thread can correspond to one object, so Let's take a look at the class that implements the Runnable interface to enable multiple threads to share the same object

Implements the Runnable interface

//实现Runnable接口public class Demo implements Runnable {  @Overridepublic void run() {for(int i=0;i<10;i++)
        {
            System.out.println(Thread.currentThread().getName()+"正在跑");
        }

    }
}//测试类public class Test{public static void main(String[] args)
    {
        Demo d=new Demo();  //创建对象Thread thread1=new Thread(d); //为对象创建一个线程Thread thread2=new Thread(d);   //创建另外一个线程//同时启动两个线程thread1.start();
        thread2.start();
    }
}
Copy after login

It can be clearly seen from the above that an object of a class that implements the Runnable interface can be shared by multiple threads. It is not as simple as inheriting the Thread class and only using it for one thread.

The creation method

is created directly in the main method. If the object of the ordinary class created is outside, it must be final modified, which allows multiple threads to share an object at the same time. , this is the same as implementing the Runnable interface. At this time, you need to control the synchronization conditions. If you define an object in the run method, then one thread corresponds to an object, which has the same effect as inheriting the Thread class. So you can freely choose according to the conditions

//普通的一个类public class Simple {public void display()
    {for(int i=0;i<10;i++)
        {
            System.out.println(Thread.currentThread().getName()+"正在跑");
        }
    }
}//线程测试类public class Test {public static void main(String[] args) {    //如果在外面必须使用final,当然也可以直写在run方法中,不过写在外面可以实现多个线程共享一个对象//写在run方法中当前对象只能为一个线程使用,和继承Thread类一样的效果final Simple simple=new Simple(); 
        
        //下面创建使用同一个对象创建同两个线程,实现多个线程共享一个对象,和实现Runnable接口一样的效果Thread t1=new Thread(){public void run() {
                simple.display();
            };
        };
        
        Thread t2=new Thread(){public void run() {
                simple.display();
            };
        };        //启动这两个线程t1.start();   
        t2.start();
    }}
Copy after login

Commonly used methods

  • static void sleep(long mils) Make the running thread sleep for mils milliseconds, but it should be noted here that if the thread is locked, sleeping the thread will not release the lock

  • String getName() Get the name of the thread. This method has been used in the above program

  • void setName(String name) Set the name of the running thread to name

  • start() Start the thread. The creation of the thread does not mean the starting of the thread. Only by calling the start() method can the thread really start running.

  • long getId() Returns the identifier of the thread

  • ##run() The code executed by the thread is placed in the run() method. The calls in the run method are ordered and are executed in the order in which the program runs.

Use

Use the above method to create an instance

//线程的类,继承Threadpublic class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name:   " + this.getName()
                    + "   Thread-id:    " + this.getId());try {this.sleep(1000); // 线程休眠1秒} catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}//线程测试的类public class Test {public static void main(String[] args) {
        MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字MyThread1 t2 = new MyThread1();
        t2.setName("第二个线程");

        t1.start(); // 启动线程,开始运行t2.start();

    }
}
Copy after login
  • ##void join()

    Wait for the thread to terminate before running other threads

  • void join(long mils)

    The time to wait for the thread is mils milliseconds , once this time has passed, other threads execute normally

  • ##Use
//线程类public class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name:   " + this.getName()
                    + "   Thread-id:    " + this.getId());try {this.sleep(1000); // 线程休眠1秒} catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}//测试类public class Test {public static void main(String[] args) {
        MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字t1.start(); // 启动线程,开始运行try {
            t1.join();   //阻塞其他线程,只有当这个线程运行完之后才开始运行其他的线程} catch (InterruptedException e) {
            e.printStackTrace();
        }for (int i = 0; i < 10; i++) {
            System.out.println("主线程正在运行");
        }

    }
}//输出结果/*Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9Thread-Name:   第一个线程   Thread-id:    9主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行 */
Copy after login

    getPriority()
  • Get the current thread priority

  • setPriority(int num)
  • Change the priority of the thread (0-10). The default is 5. The higher the priority, the higher the chance of obtaining CPU resources.

  • Use
//线程类public class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name:   " + this.getName()
                    + "   Thread-id:    " + this.getId());try {this.sleep(1000); // 线程休眠1秒} catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}//测试类public class Test {public static void main(String[] args) {
        MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字MyThread1 t2 = new MyThread1();
        t2.setName("第二个线程");

        t2.setPriority(8);   //设置第二个线程的优先级为8,第一个线程的优先级为5(是默认的)t1.start();
        t2.start();

    }
}/* * 从上面的运行结果可以看出大部分的第二个线程都是在第一个线程之前开始执行的,也就是说优先级越高获得cpu执行的几率就越大 * /
Copy after login

    setDaemon(boolean)
  • Whether to set it as a daemon thread. If it is set to a daemon thread, the daemon thread will also be destroyed when the main thread is destroyed

  • isDaemon ()
  • Determine whether it is a daemon thread

  • Use
//测试类public class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name:   " + this.getName()
                    + "   Thread-id:    " + this.getId());try {
                Thread.sleep(1000);  //休眠一秒,方便主线程运行结束} catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}public class Test {public static void main(String[] args) {
        MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字t1.setDaemon(true);
        t1.start();for (int i = 0; i < 1; i++) {
            System.out.println(i);
        }

    }
}//结果:/* 0123456789Thread-Name:   第一个线程   Thread-id:    9*//* * 从上面的结果可以看出,一旦主线程结束,那么守护线程就会自动的结束 *
Copy after login

The above is the detailed content of The definition and common methods of Thread. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Getting started with Java crawlers: Understand its basic concepts and application methods Getting started with Java crawlers: Understand its basic concepts and application methods Jan 10, 2024 pm 07:42 PM

A preliminary study on Java crawlers: To understand its basic concepts and uses, specific code examples are required. With the rapid development of the Internet, obtaining and processing large amounts of data has become an indispensable task for enterprises and individuals. As an automated data acquisition method, crawler (WebScraping) can not only quickly collect data on the Internet, but also analyze and process large amounts of data. Crawlers have become a very important tool in many data mining and information retrieval projects. This article will introduce the basic overview of Java crawlers

What are the differences between Runnable and Thread in Java? What are the differences between Runnable and Thread in Java? May 07, 2023 pm 05:19 PM

There are two ways to implement multi-threading in Java, one is to inherit the Thread class, and the other is to implement the Runnable interface; the Thread class is defined in the java.lang package. As long as a class inherits the Thread class and overrides the run() method in this class, it can implement multi-threaded operations. However, a class can only inherit one parent class, which is a limitation of this method. Let’s look at an example: packageorg.thread.demo;classMyThreadextendsThread{privateStringname;publicMyThread(Stringname){super();this

Start a new thread using java's Thread.start() function Start a new thread using java's Thread.start() function Jul 24, 2023 pm 11:01 PM

Use Java's Thread.start() function to start a new thread. In Java, we can use multi-threading to execute multiple tasks concurrently. Java provides the Thread class to create and manage threads. The start() function in the Thread class is used to start a new thread and execute the code in the run() method of the thread. Code example: publicclassMyThreadextendsThread{@Overr

How does Thread generate an interface in java? How does Thread generate an interface in java? May 17, 2023 pm 12:49 PM

In java, when it comes to threads, Thread is essential. A thread is a lighter scheduled executor than a process. Why use threads? By using threads, you can separate resource allocation and execution scheduling in operating system processes. Each thread can not only share process resources (memory address, file I/O, etc.), but can also be scheduled independently (thread is the basic unit of CPU scheduling). Note 1. Thread is the most important class for making threads, and the word itself also represents thread. 2. The Thread class implements the Runnable interface. Instance publicclassThreadDemoextendsThread{publicvoidrun(){for(inti=0

Understanding Spring MVC: A preliminary exploration into the nature of this framework Understanding Spring MVC: A preliminary exploration into the nature of this framework Dec 29, 2023 pm 04:27 PM

Understanding SpringMVC: A preliminary exploration of the essence of this framework requires specific code examples. Introduction: SpringMVC is a Java-based web application development framework. It adopts the MVC (Model-View-Controller) design pattern and provides a flexible and scalable way to build web applications. This article will introduce the basic working principles and core components of the SpringMVC framework, and combine it with actual code examples to help readers better understand the nature of this framework.

Java uses the start() function of the Thread class to start a new thread Java uses the start() function of the Thread class to start a new thread Jul 24, 2023 am 11:31 AM

Java uses the start() function of the Thread class to start a new thread. In Java, multi-threading is a concurrent execution method that can perform multiple tasks at the same time. In order to implement multi-threading, the Thread class is provided in Java, through which threads are created and controlled. Among them, the start() function is used to start a new thread. The function of the start() function is to put the thread into the ready state and automatically call the thread's run() method. When a thread calls start(

Five ways to fix Thread Stuck in Device Driver blue screen Five ways to fix Thread Stuck in Device Driver blue screen Mar 25, 2024 pm 09:40 PM

Some users reported that after installing Microsoft's March Win11 update patch KB5035853, a blue screen of death error occurred, with &quot;ThreadStuckinDeviceDriver&quot; displayed on the system page. It is understood that this error may be caused by hardware or driver issues. Here are five fixes that will hopefully resolve your computer blue screen problem quickly. Method 1: Run system file check. Run the [sfc/scannow] command in the command prompt, which can be used to detect and repair system file integrity issues. The purpose of this command is to scan and repair any missing or damaged system files, helping to ensure system stability and normal operation. Method 2: 1. Download and open the &quot;Blue Screen Repair Tool&quot;

Overview of Thread threads in C# Overview of Thread threads in C# Feb 18, 2024 am 11:20 AM

Introduction to Thread in C#, specific code examples are required. In C#, Thread (thread) is an independent execution path for executing code. By using threads, we can execute multiple tasks in parallel and improve the performance and responsiveness of the program. This article will introduce the basic concepts, usage and related code examples of Thread threads in C#. 1. The basic concept of threads Threads are the basic execution units in the operating system. In C#, the Thread class is the primary tool for creating and manipulating threads. Threads can

See all articles