By GokiSoft.com| 21:09 20/03/2023|
Java Advanced

[Source Code] Tìm hiểu Thread trong Java - C2206L

Nội dung kiến thức học
	- Chữa bài tập
	- Thread
		- Multi Thread
		- Sync Multi Thread
======================================================
May tinh:
	App1 -> process -> tien trinh -> pid1
	App2 -> pid2
		Java: Multi Thread (5-7 Thread trong 1 App)
			sub process -> Thread
			Main Thread -> process
				T1
				T2
				T3
				...
	App3 -> pid3
	...

	CPU:
		1 core -> tai 1 thoi diem -> xu ly dc 1 dong lenh 
		2 core -> 2 command line
		3 core -> 3 command line
		5 core ..
		7 core
		...

	Giai thuat trong lap trinh: FIFO, LIFO, Round Robin, ...
	Toc do xu ly CPU: 1 trieu lenh/1 giay
	moi 1 app -> 1s -> 200K lenh/1 gay -> 

=======================================================
Main --------------------
t1      ---------------------------
t2        ------------------
t3     -------------------------

Join:
Main ---						   ---					--------------
t1      ---------------------------
t2        							  ------------------
t3     														-------------------------

========================================================
VCB: 100 trieu
10 The ATM -> 10 nguoi
Bai toan:
	10 nguoi -> cung dong thoi rut tien -> 10 ATM
	10 -> 10 transaction -> trong cung 1 thoi diem -> 100 trieu
		-> 10 * 100 trieu -> 1 ty
		-> TK ngan hang: -900 trieu
Yêu cầu bài toán:
	Thread 1 -> Sinh ngẫu nhiêu 1 số tự nhiên từ 0 -> 100
	Thread 2 -> Hiển thị bình phương số tự nhiên vừa đc sinh ra trong Thread 1

	Synchronized:

	T1 -> 3        T1 -> 5        T1 -> 6
			T2 -> 9       T2 -> 25

	Thread
		wait() -> pause
		notify() & notifyAll() -> chuyen tu wait() -> running()

	Synchronized:
		- Function: 10 thread -> invoke 1 function -> queue
		- Object: 10 thread -> invoke 1 block sync object -> queue

Gia thiet xay ra:
T2 -> synchronized -> notifyAll() -> wait()                                          -> rad -> bp(rad) -> notifyAll() -> wait()
T1 -> synchronized                         -> rad -> in(rad) -> notifyAll() -> wait()        

#CustomThread.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 diepvan
 */
public class CustomThread extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Custom Thread > " + i);
        }
    }
    
}

#SharedData.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 diepvan
 */
public class SharedData {
    int x = 0;
    
    /**
     * t1, t2, t3 -> goi toi function -> queue
     * @param delta
     */
    public synchronized void changeValue(int delta) {
        System.out.println("x = " + x + ", delta = " + delta);
        x += delta;
        System.out.println("x = " + x);
    }
}

#Test01.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 diepvan
 */
public class Test01 {
    public static void main(String[] args) {
        //Phan 1: Co che hoat dong multi thread -> Cach tao Thread
        System.out.println("Main Start");//Main thread
        
        //Phan 2: Xac dinh Thread -> live & die
        //Tai thoi diem nay -> T1 -> Khai bao -> Chua ton tai
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("T1 > " + i);
                }
                //t1 -> die -> Xu ly het lenh trong run()
                //hoac t1.selfStop()
            }
        });
        //Main
        //Toi khi goi t1.start() -> t1 -> exist -> live
        t1.start();//Main, T1 -> Live
        //t1 -> die -> trong 1 so TH sau
        //Hoac t1.stop() -> die
        //Chu y: t1 -> stop -> khong the nao cho song lai dc -> t1.start() -> Error
        
        //Phan 2: Xac dinh so Thread dang ton tai trong he thong -> Tai tung thoi diem
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("T2 > " + i);
                }
            }
        });
        //Main -> live, t1: co the live | die
        
        t2.start();//Main -> live, t2 -> live, t1: co the live | die
        
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("T3 > " + i);
                }
            }
        });
        //Main -> live, t1&t2: co the live | die
        
        t3.start();//Main -> live, t3 -> live, t1&t2: co the live | die
        
        System.out.println("Main Stop");
        //Main -> die, t1, t2, t3: co the live | die
        //t1.isAlive();t2.isAlive();t3.isAlive();
    }
}

#Test02.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 diepvan
 */
public class Test02 {
    public static void main(String[] args) {
        //Cach 1:
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Test02.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    System.out.println("T1 > " + i);
                }
            }
        });
        t1.start();
        
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Test02.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //Cach 2: Lambda expression
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("T1 > " + i);
            }
        });
        t2.start();
        
        try {
            t2.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Test02.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //Cach 3:
        CustomThread t3 = new CustomThread();
        t3.start();
    }
}

#Test03.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 diepvan
 */
public class Test03 {

    public static void main(String[] args) {
        SharedData sharedData = new SharedData();

//        for (int i = 0; i < 10; i++) {
//            sharedData.changeValue(1);
//        }
//        
//        for (int i = 0; i < 10; i++) {
//            sharedData.changeValue(1);
//        }
//        
//        for (int i = 0; i < 10; i++) {
//            sharedData.changeValue(1);
//        }

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                sharedData.changeValue(1);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                sharedData.changeValue(1);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                sharedData.changeValue(1);
            }
        }).start();
    }
}

#Thread2.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 diepvan
 */
public class Thread2 extends Thread{
    SharedData sharedData;

    public Thread2(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (sharedData) {
                sharedData.notifyAll();
                try {
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                int rad = sharedData.getRad();
                System.out.println("T2 > " + rad + " -> " + (rad * rad));
            }
        }
        
        System.out.println("T2 stop");
        
        synchronized (sharedData) {
            sharedData.notifyAll();
        }
    }
    
}

#Thread1.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.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author diepvan
 */
public class Thread1 extends Thread{
    SharedData sharedData;

    public Thread1(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run() {
        Random random = new Random();
        
        for (int i = 0; i < 10; i++) {
            synchronized (sharedData) {
                int rad = random.nextInt(100);
                System.out.println("T1 > " + rad);
                sharedData.setRad(rad);
                
                sharedData.notifyAll();
                try {
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println("T1 stop");
        
        synchronized (sharedData) {
            sharedData.notifyAll();
        }
    }
    
}

#Test4.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 diepvan
 */
public class Test4 {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
        Thread1 t1 = new Thread1(sharedData);
        Thread2 t2 = new Thread2(sharedData);
        
        t1.start();
        t2.start();
    }
}
Tags:

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

5

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