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:

Java Program to Perform Left Rotation on a Binary Search Tree
An Intro to Spring Cloud Zookeeper
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Find the Edge Connectivity of a Graph
StringBuilder vs StringBuffer in Java
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
Converting Between Byte Arrays and Hexadecimal Strings in Java
Java – Delete a File
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Lớp HashMap trong Java
Reversing a Linked List in Java
Bootstrap a Web Application with Spring 5
Java Program to Implement the String Search Algorithm for Short Text Sizes
Java Stream Filter with Lambda Expression
Java Program to Perform Sorting Using B-Tree
Java Program to Implement EnumMap API
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Extract network card address
Java Program to Generate N Number of Passwords of Length M Each
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Java Program to implement Bi Directional Map
A Custom Data Binder in Spring MVC
Handling Errors in Spring WebFlux
Getting the Size of an Iterable in Java
Java Switch Statement
Recommended Package Structure of a Spring Boot Project
Spring Boot - Internationalization
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Implement Circular Doubly Linked List
Biểu thức Lambda trong Java 8 – Lambda Expressions
A Guide to Java HashMap
Java Program to Implement Gabow Algorithm

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.