By GokiSoft.com| 15:41 17/07/2023|
Java Advanced

[Share Code] Tìm hiểu về đa luồng trong Java - C2209I

Có phải trong 1 lúc => Máy tính đang xử lý 10 ứng dụng không?
	Phải -> Thì hoạt động như nào
	Không -> Tại sao nó cho chúng ta cảm giác 10 ứng dụng đang hoạt động //

OS:
	Ứng dụng 1 -> p1 -> game Liên Minh
		- Thay đổi UI -> Thread -> T1
		- nghe nhạc -> T2
		- xem phim -> T3
		- chat -> T4
		- tải hình ảnh -> T5
		- giao tiếp vs server (API) -> T6
		...
	Ứng dụng 2 -> p2
	...
	Ứng dụng N -> pN

CPU:
	celeron -> 1 core -> tại 1 thời điểm -> Xử lý đc 1 lệnh
	dual core
	core 2 dual
	i3
	i5
	i7
	...

1 công nhân -> thực hiện N job (N công việc - worker) - round robin (LIFO, FIFO)
CPU -> 1 triệu lệnh/1 giây
30 job (30 ứng dụng) -> xử lý nhất nhanh

Nội dung kiến thức Thread
	- Thread là gì, tiến trình là gì?
	- Tạo thread mới
		- 3 cách tạo 1 thread
	- Thread tồn tài khi nào & Kết thúc khi nào
	- Xác định số luồng xuất hiện trong từng thời điểm
		- Xác định dòng code đang ở thread nào?
	- Trạng thái của 1 Thread
	- Join thread
		TM ---------------------------------------------------
		T1        --------------------------------
		T2			---------------------------------------------------
		T3				----------------------------------------------------------


		TM ---------------								------------------------------------
		T1        -------(Join)-------------------------
		T2													---------------------------------
		T3														---------------------
	- Đồng bộ thread
		- Đồng bộ trên function (method)
		- Đồng bộ theo object (Khó)
			- notify
			- notifyAll
			- wait

ATM: 2 triệu
	T1 -> 2
	T2 -> 2
	T3
	T4
	..
	T10 -> 2

Tổng:20 triệu -> 18 triệu -> Giải thể

T1, T2, ..., T10 -> queue (T1 -> T2 -> T3 ... -> T10)

#Main.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.java2.lesson04;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 */
public class Main {

    static class CustomThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("T3 > " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public static void main(String[] args) {
        //process -> Tao ra 1 main thread (Luồng chính)
        System.out.println("START APP");
        //Main thread -> Dang ton tai
        //Cach 1: Tao thread 1
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("T1 > " + i);
                }
            }
        });
        //Main thread
        t1.start();//chi duoc goi duy nhat 1 lan
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        //t1.stop();
        //Main thread & T1
        //Dang bien dich toi day -> Tai thoi diem nay -> Co thread nao dang ton tai???
        //Cach 2: Tao thread 2
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("T2 > " + i);
                }
            }
        }).start(); //Main thread, T1 (Có thể tồn tại hoặc đã stop), T2

        CustomThread t3 = new CustomThread();
        t3.start(); //Main thread, T1 (Có thể tồn tại hoặc đã stop), T2 (Tương tự), T3
//        for (int i = 0; i < 10; i++) {
//            System.out.println("T3 > " + i);
//        }

        System.out.println("END APP");
    }

    static void testOneThread() {
        //process -> Tao ra 1 main thread (Luồng chính)
        System.out.println("START APP");

        for (int i = 0; i < 10; i++) {
            System.out.println("T1 > " + i);
        }

        for (int i = 0; i < 10; i++) {
            System.out.println("T2 > " + i);
        }

        for (int i = 0; i < 10; i++) {
            System.out.println("T3 > " + i);
        }

        System.out.println("END APP");
    }
}

#Test.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.java2.lesson04;

/**
 *
 * @author teacher
 */
public class Test {
    static class SharedData {
        int x;

        public SharedData() {
            x = 0;
        }
        
        public synchronized void changeX(int change) {
            System.out.println("x = " + x + ", change = " + change);
            x += change;
            System.out.println("x = " + x);
        }
    }
    
    static class Thread1 extends Thread {
        SharedData sharedData;

        public Thread1(SharedData sharedData) {
            this.sharedData = sharedData;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                sharedData.changeX(1);
            }
        }
    }
    static class Thread2 extends Thread {
        SharedData sharedData;

        public Thread2(SharedData sharedData) {
            this.sharedData = sharedData;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                sharedData.changeX(-1);
            }
        }
    }
    
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
        Thread1 t1 = new Thread1(sharedData);
        Thread1 t2 = new Thread1(sharedData);
        Thread1 t3 = new Thread1(sharedData);
        
        t1.start();
        t2.start();
        t3.start();
//        for (int i = 0; i < 10; i++) {
//            sharedData.changeX(1);
//        }
//        
//        for (int i = 0; i < 10; i++) {
//            sharedData.changeX(-1);
//        }
//        
//        for (int i = 0; i < 10; i++) {
//            sharedData.changeX(1);
//        }
    }
}
Tags:



Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó