Home >Java >javaTutorial >How to use threads in Java

How to use threads in Java

PHPz
PHPzOriginal
2024-02-18 12:47:05732browse

How to use threads in Java

How to use Thread in Java, specific code examples

  1. Introduction
    In Java, multi-threaded programming is a powerful way to Improve program efficiency and concurrency. The Thread class is the core class in Java used to create and manage threads. This article will introduce the use of the Thread class in detail and provide some specific code examples.
  2. Creating Thread
    Thread objects can be created in two ways: inheriting the Thread class and implementing the Runnable interface. Inheriting the Thread class is a simple way, but since Java only supports single inheritance, this method will limit the scalability of the code. Implementing the Runnable interface can avoid this problem, because Java supports the implementation of multiple interfaces.

The following is a code example of using two methods to create a thread:

// 继承Thread类
class MyThread extends Thread {
    public void run(){
        // 线程执行的代码
    }
}

// 实现Runnable接口
class MyRunnable implements Runnable {
    public void run(){
        // 线程执行的代码
    }
}

// 创建线程并启动
public static void main(String[] args){
    // 创建继承Thread类的线程
    MyThread thread1 = new MyThread();
    thread1.start();

    // 创建实现Runnable接口的线程
    MyRunnable runnable = new MyRunnable();
    Thread thread2 = new Thread(runnable);
    thread2.start();
}

In the above code, the thread created by inheriting the Thread class directly calls the start method to start the thread. , and a thread created by implementing the Runnable interface needs to first create a Thread object, pass the object that implements the Runnable interface as a parameter to the Thread constructor, and then call the start method of the Thread object to start the thread.

  1. Life cycle of thread
    A thread will go through multiple states after it is created, and these states are called the life cycle of the thread. Common thread states are: New, Runnable, Running, Blocked and Terminated.

The following is a simple example showing the life cycle of a thread:

class MyThread extends Thread {
    public void run(){
        System.out.println("线程执行中");

        try {
            Thread.sleep(1000); // 线程等待1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("线程执行结束");
    }
}

public static void main(String[] args){
    MyThread thread = new MyThread();
    System.out.println("线程状态:" + thread.getState()); // 输出线程状态为New
    thread.start();
    System.out.println("线程状态:" + thread.getState()); // 输出线程状态为Runnable
    // 等待线程执行结束
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("线程状态:" + thread.getState()); // 输出线程状态为Terminated
}

In the above code, after a new thread is created and started, the status of the thread is first output is New, and then the output status is Runnable. After calling the thread.join() method and waiting for the thread execution to end, the final output status is Terminated.

  1. Thread synchronization and mutual exclusion
    In multi-threaded programming, thread synchronization and mutual exclusion are very important concepts. When multiple threads access shared resources at the same time, in order to avoid race conditions and data inconsistencies, appropriate synchronization measures need to be taken.

Java provides mechanisms such as the synchronized keyword and Lock interface to achieve thread synchronization and mutual exclusion. The following is an example of using the synchronized keyword for thread synchronization:

class Counter {
    private int count = 0;

    // 线程安全的方法
    public synchronized void increment(){
        count++;
    }

    public int getCount(){
        return count;
    }
}

public static void main(String[] args){
    Counter counter = new Counter();

    Runnable runnable = () -> {
        for(int i=0; i<10000; i++){
            counter.increment();
        }
    };

    Thread thread1 = new Thread(runnable);
    Thread thread2 = new Thread(runnable);

    thread1.start();
    thread2.start();

    try {
        thread1.join();
        thread2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("计数器的值:" + counter.getCount()); // 输出:20000
}

In the above code example, a thread-safe Counter class is defined, in which the increment method uses the synchronized keyword to synchronize shared data. Two threads called the Counter object at the same time. Each thread performed 10,000 increment operations on count, and finally output the correct result of 20,000.

  1. Interruption of threads
    Java provides a mechanism to interrupt a running thread. You can call the interrupt method of the Thread class to send an interrupt signal. The interrupted thread can determine whether an interrupt signal has been received by calling the isInterrupted method, and then take appropriate actions as needed.

The following is a sample code that shows how to interrupt a thread:

class MyThread extends Thread {
    public void run(){
        while(!isInterrupted()){
            System.out.println("线程运行中");
            try {
                Thread.sleep(1000); // 线程等待1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
        System.out.println("线程中断");
    }
}

public static void main(String[] args){
    MyThread thread = new MyThread();
    thread.start();

    try {
        Thread.sleep(5000); // 主线程等待5秒
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    thread.interrupt(); // 中断线程
}

In the above code, after a new thread is created and started, the main thread waits for 5 seconds Then the child thread is interrupted.

Summary:
This article introduces the use of the Thread class in Java and provides some specific code examples. You can create a thread by inheriting the Thread class or implementing the Runnable interface, and start the thread by calling the start method. Understanding the thread life cycle and the concepts of thread synchronization and mutual exclusion is very important for writing robust multi-threaded programs. At the same time, understanding how to interrupt threads is also an important knowledge point in multi-threaded programming. Mastering these contents can help developers use multi-threaded programming to improve program efficiency and concurrency.

The above is the detailed content of How to use threads in Java. 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