search
HomeJavajavaTutorialThe definition and common methods of Thread

The definition and common methods of Thread

Jun 21, 2017 am 09:36 AM
threadPreliminary 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();     //启动线程}
}

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();
    }
}

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();
    }}

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();

    }
}
  • ##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主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行 */

    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执行的几率就越大 * /

    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*//* * 从上面的结果可以看出,一旦主线程结束,那么守护线程就会自动的结束 *

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
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
Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Apr 19, 2025 pm 08:06 PM

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Apr 19, 2025 pm 07:57 PM

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Apr 19, 2025 pm 07:54 PM

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...

In Java programming, how to stop subsequent code execution when student ID is repeated?In Java programming, how to stop subsequent code execution when student ID is repeated?Apr 19, 2025 pm 07:51 PM

How to stop subsequent code execution when ID is repeated in Java programming. When learning Java programming, you often encounter such a requirement: when a certain condition is met,...

Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Apr 19, 2025 pm 07:48 PM

In-depth discussion of final consistency: In the distributed system of application scenarios and implementation methods, ensuring data consistency has always been a major challenge for developers. This article...

After the Spring Boot service is running for a period of time, how to troubleshoot?After the Spring Boot service is running for a period of time, how to troubleshoot?Apr 19, 2025 pm 07:45 PM

The troubleshooting idea of ​​SSH connection failure after SpringBoot service has been running for a period of time has recently encountered a problem: a Spring...

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.