Luồng Daemon (Daemon Thread) trong Java

1. Luồng Daemon (Daemon Thread) là gì?

Java chia thread làm 2 loại: một loại thông thường và Daemon Thread. Chúng chỉ khác nhau ở cách thức ngừng hoạt động. Trong một chương trình các luồng thông thường và luồng Daemon chạy song song với nhau. Khi tất cả các luồng thông thường kết thúc, mọi luồng Daemon cũng sẽ bị kết thúc theo bất kể nó đang làm việc gì.

Sử dụng setDaemon(boolean) để xác định một luồng là Daemon hoặc không. Chú ý, bạn chỉ có thể gọi hàm setDeamon(boolean) khi thread chưa được chạy. Điều đó có nghĩa là khi thread đã chạy bạn không thể chuyển luồng từ non-daemon sang daemon và ngược lại. Khi bạn cố gắng thay đổi trạng thái của luồng, một ngoại lệ IllegalThreadStateException được ném ra và luồng kết thúc xử lý.

Khi một luồng mới được tạo ra, nó được thừa hưởng đặc tính daemon từ luồng cha.  Như vậy khi bạn tạo một luồng trong hàm main của 1 class nó vốn là luồng non-daemon , vì vậy thread tạo ra mặc định cũng là non-daemon . Như vậy nếu bạn tạo một luồng mới trong một luồng Daemon, mặc định nó cũng sẽ là Daemon .

2. Luồng Daemon thường dùng làm gì?

Một trong các luồng Deamon quan trọng của Java đó là luồng gom rác, nghĩa là gom các tài nguyên không còn sử dụng để giải phóng bộ nhớ. Khi tất cả các luồng người dùng không còn hoạt động nữa luồng gom rác cũng bị dừng theo.

3. Ví dụ minh họa

3.1. Tạo một luồng WorkingThread

package com.maixuanviet.daemonthread;
 
public class WorkingThread implements Runnable {
 
    @Override
    public void run() {
        while (true) {
            processSomething();
        }
    }
 
    private void processSomething() {
        try {
            System.out.println("Processing working thread");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
}

3.2. Chương trình Non-Daemon Thread

package com.maixuanviet.daemonthread;

public class NonDaemonThreadTest {
public static void main(String[] args) throws InterruptedException {
Thread dt = new Thread(new WorkingThread(), “My Non-Daemon Thread”);
dt.start();

// continue program
Thread.sleep(3000);
System.out.println(“>><< Finishing main program"); } } [/code]

Thực thi chương trình trên:

Processing working thread
Processing working thread
Processing working thread
Processing working thread
Processing working thread
Processing working thread
>><< Finishing main program Processing working thread Processing working thread Processing working thread .... [/code]

Như bạn thấy luồng Non-DaemonThread chạy song song với MainThread. Khi MainThread kết thúc thì luồng Non-DaemonThread vẫn còn tiếp tục xử lý cho đến khi hoàn thành.

3.3. Chương trình Daemon Thread

package com.maixuanviet.daemonthread;

public class DaemonThreadTest {

public static void main(String[] args) throws InterruptedException {
Thread dt = new Thread(new WorkingThread(), “My Daemon Thread”);
dt.setDaemon(true);
dt.start();

// continue program
Thread.sleep(3000);
System.out.println(“>><< Finishing main program"); } } [/code]

Thực thi chương trình trên:

Processing working thread
Processing working thread
Processing working thread
Processing working thread
Processing working thread
Processing working thread
>><< Finishing main program [/code]

Như bạn thấy DaemonThread chạy song song với MainThread. Khi MainThread kết thúc thì tất cả DaemonThread cũng kết thúc.

Related posts:

Hướng dẫn Java Design Pattern – Factory Method
Java Program to Implement IdentityHashMap API
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Documenting a Spring REST API Using OpenAPI 3.0
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Implement RoleUnresolvedList API
Prevent Cross-Site Scripting (XSS) in a Spring Application
Composition, Aggregation, and Association in Java
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
A Guide To UDP In Java
Immutable Objects in Java
Simultaneous Spring WebClient Calls
Different Ways to Capture Java Heap Dumps
Chương trình Java đầu tiên
Converting Between a List and a Set in Java
Java Program to Implement Sorted List
Finding Max/Min of a List or Collection
Java Program to Solve any Linear Equations
Set Interface trong Java
Apache Commons Collections MapUtils
Java Program to Perform Partition of an Integer in All Possible Ways
Java Program to Solve a Matching Problem for a Given Specific Case
Spring Boot - File Handling
Java Program to Implement Pollard Rho Algorithm
Java Program to Implement Hash Tables with Quadratic Probing
Java Program to Implement the String Search Algorithm for Short Text Sizes
How to Use if/else Logic in Java 8 Streams
Spring Boot: Customize the Jackson ObjectMapper
Java – Combine Multiple Collections
Ép kiểu trong Java (Type casting)
Java Program to Generate All Pairs of Subsets Whose Union Make the Set

1 Trackback / Pingback

  1. Lập trình đa luồng với Callable và Future trong Java – Blog của VietMX

Comments are closed.