Home > Java > javaTutorial > body text

How to use Thread function in Java for thread operations

王林
Release: 2023-06-26 14:54:10
Original
1127 people have browsed it

The Thread function in Java is a class provided by Java for creating and controlling threads. Threads can implement concurrent operations in the program and improve the running efficiency of the program. The Thread function provides many methods to facilitate thread operations. This article will introduce how to use the Thread function in Java for thread operations.

  1. Creating threads

There are two ways to create threads in Java: inheriting the Thread class and implementing the Runnable interface. Inheriting the Thread class is a simpler approach, but is limited by Java's single inheritance model. Implementing the Runnable interface is a more flexible approach that avoids this problem.

The code that inherits the Thread class is as follows:

class MyThread extends Thread {
    public void run() {
        // 线程运行的代码
    }
}

// 创建线程
MyThread thread = new MyThread();

// 启动线程
thread.start();
Copy after login

The code that implements the Runnable interface is as follows:

class MyRunnable implements Runnable {
    public void run() {
        // 线程运行的代码
    }
}

// 创建线程
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);

// 启动线程
thread.start();
Copy after login
  1. Control thread

In Java The Thread function provides some methods to easily control threads. Here are some commonly used methods.

1) sleep method: let the thread sleep for a period of time, the unit is milliseconds.

try {
    Thread.sleep(1000); // 线程睡眠1秒钟
} catch (InterruptedException e) {
    e.printStackTrace();
}
Copy after login

2) Yield method: Give up the CPU execution rights of the current thread and give other threads a chance to run.

Thread.yield();
Copy after login

3) join method: wait for another thread to finish executing before executing.

try {
    thread.join(); // 等待thread线程执行完毕后再执行
} catch (InterruptedException e) {
    e.printStackTrace();
}
Copy after login

4) interrupt method: interrupt the thread.

thread.interrupt(); // 中断线程
Copy after login
  1. Thread synchronization

Thread synchronization means that in a multi-threaded environment, since the execution of multiple threads is uncertain, two or more threads may appear. Threads modify the same shared resource at the same time, resulting in data inconsistency. Java provides the synchronized keyword and lock mechanism to solve this problem.

class MyThread implements Runnable {
    private Integer count = 0;

    public synchronized void run() {
        for (int i = 0; i < 10; i++) {
            count++; // 对共享资源进行操作
            System.out.println(Thread.currentThread().getName() + " count: " + count);
            Thread.yield();
        }
    }
}

// 创建两个线程
MyThread runnable = new MyThread();
Thread t1 = new Thread(runnable, "Thread1");
Thread t2 = new Thread(runnable, "Thread2");

// 启动两个线程
t1.start();
t2.start();
Copy after login

In the above code, we use the synchronized keyword to ensure that multiple threads' access to the count variable is mutually exclusive.

  1. Thread collaboration

Thread collaboration refers to the collaboration between multiple threads, allowing them to execute in a certain order. The Thread function in Java provides wait and notify methods to achieve thread cooperation.

class MyThread implements Runnable {
    private boolean running = true;

    public synchronized void run() {
        while (running) {
            try {
                System.out.println(Thread.currentThread().getName() + " is running");
                wait(); // 等待其他线程唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + " is stopped");
    }

    public synchronized void stop() {
        running = false;
        notify(); // 唤醒其他线程
    }
}

// 创建线程
MyThread runnable = new MyThread();
Thread thread = new Thread(runnable);

// 开始线程
thread.start();

// 停止线程
runnable.stop();
Copy after login

In the above code, we use the wait method to let the thread wait for other threads to wake up, and use the notify method to wake up other threads.

  1. Thread pool

Thread pool is a common thread management method, which allows the reuse of threads and improves the efficiency of the program. The Thread function in Java provides the ThreadPoolExecutor class to implement a thread pool.

class MyTask implements Runnable {
    private Integer id;

    public MyTask(Integer id) {
        this.id = id;
    }

    public void run() {
        System.out.println("Task " + id + " is running");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(5);

// 提交任务
for (int i = 0; i < 10; i++) {
    executor.submit(new MyTask(i));
}

// 关闭线程池
executor.shutdown();
Copy after login

In the above code, we create a thread pool by calling the newFixedThreadPool method of Executors, then submit the task, and finally close the thread pool.

Summary

The Thread function in Java provides many methods to facilitate thread operations. In actual programming, we need to choose different thread models according to our own needs, and at the same time, we must pay attention to issues such as thread synchronization and thread collaboration to ensure the correctness and efficiency of program operation.

The above is the detailed content of How to use Thread function in Java for thread operations. For more information, please follow other related articles on the PHP Chinese website!

source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!