By GokiSoft.com| 10:17 11/09/2021|
Java Advanced

[Share Code] Tìm hiểu Thread - Đồng bộ Thread - Synchonized _ Wait - NotifyAll - Lập trình Java nâng cao - C2009G



- Tìm hiểu qua cơ chế hoạt của OS + CPU
	-> Chrome                             -> Tap hop khoi lenh -> process -> Tien trinh
	-> Slide Show
	-> Netbean -> Code
	-> Sublime Text -> Soan thao
	-> Media Player
	...
5 phan dang dc tren PC -> chay doc lap (//)

- CPU -> 1 core -> xu ly 1 lenh/tai 1 thoi diem
=======================================================
5 PM -> 5 tien trinh (5 pid)
FIFO, LIFO, Round Robin

Toc do xu ly CPU -> 1 trieu lenh/1 s

=======================================================
Viet 1 PM Game:
- Play MP3 -> 20 phut
- Download Youtube -> 500M -> 5 phut
- A -> B
- C -> D
- Thao tac tren man hinh
=> Ko ai choi game:

Quan sat 1 game that hien nay:
- Background sound -> 						Thread -> T1
- Tai du lieu tu internet -> ve             Thread -> T2
- Thao tac dc tren man hinh                 Thread -> T3 ...
- chat dc vs nhau
- choi game -> van dang chuyen dong
...

T5 -> Chay doc lap (//)
Khoi lenh trong 1 Thread -> Thu tu...
========================================================

M----------------------
T1  ------------------------
T2      ---------------------------
T3 --------------
T4    -------------------


M ------               ----------------------
T1      ---------------

Bai toan dong bo da Thread

Quay ban ve xem phim:
10 den mua ve: -> Kho khan -> Sai sot cho nguoi ban ve
Queue -> xep hang de mua -> dong bo -> Biet cach xu ly -> chuan, ko bi sai sot

Data -> luu thong tin
x

T1 -> T3: x tang + giam gia tri cua x -> Sai ...

=========================================================
Bài toán:
T1 -> Sinh ra 1 số ngẫu nhiên N
T2 -> Hiển thị ra bình phương số N đó.
Yêu cầu:

T1...rad...             ...rad...             ...rad...
T2         ...rad*rad...         ...rad*rad...

=========================================================

T1                  ..rad..notifyAll..wait                           ..sync..rad..notifyAll..wait
T2 ..notifyAll..wait                      ..BT..sync..notifyAll..wait                            ...

T1 ..rad..notifyAll..wait                 ..rad..notifyAll..wait
T2                       ..notifyAll..wait                      ..BT..sync..notifyAll..wait

'\n'

"\n"


Phần 1:


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

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

/**
 *
 * @author Diep.Tran
 */
public class Main {

    public static void main(String[] args) {
        //Main Thread
        System.out.println("Main thread start");

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //Noi bat dau xu ly cua Thread 1
                for (int i = 0; i < 10; i++) {
                    System.out.println("T1 > " + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                //Noi bat dau xu ly cua Thread 2
                for (int i = 0; i < 10; i++) {
                    System.out.println("T2 > " + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });
        
        CustomThread t3 = new CustomThread();
        t3.setName("T3");
        CustomThread t4 = new CustomThread();
        t4.setName("T4");
        
        t1.start();//Bat dau chay Thread 1 + Main Thread
        try {
            t1.join();//T1 chay xong -> cho phep Main tiep tuc
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        t2.start();//Bat dau chay Thread 2 + T1 + Main Thread
        try {
            t2.join();//T2 chay xong -> cho phep Main tiep tuc
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        t3.start();
        t4.start();

        System.out.println("Main thread stop");
    }
}


#CustomThread.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

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

/**
 *
 * @author Diep.Tran
 */
public class CustomThread extends Thread {

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

}

Phần 2:

#Test01.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

/**
 *
 * @author Diep.Tran
 */
public class Test01 {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
//        for (int i = 0; i < 10; i++) {
//            sharedData.addMore(1);
//        }
        TestThread t1 = new TestThread(sharedData);
        TestThread t2 = new TestThread(sharedData);
        TestThread t3 = new TestThread(sharedData);
        TestThread t4 = new TestThread(sharedData);
        TestThread t5 = new TestThread(sharedData);
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}


#SharedData.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

/**
 *
 * @author Diep.Tran
 */
public class SharedData {
    int rad;
    int x;
    
    public synchronized void addMore(int delta) {
        System.out.println("x = " + x + ", delta: " + delta);
        x+=delta;
        System.out.println("x = " + x);
    }

    public int getRad() {
        return rad;
    }

    public void setRad(int rad) {
        this.rad = rad;
    }
}


#TestThread.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

/**
 *
 * @author Diep.Tran
 */
public class TestThread extends Thread{
    SharedData sharedData;

    public TestThread(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            sharedData.addMore(1);
        }
    }
    
}

Phần 3:

#ThreadTwo.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

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

/**
 *
 * @author Diep.Tran
 */
public class ThreadTwo extends Thread {
    SharedData sharedData;

    public ThreadTwo(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(ThreadTwo.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                int rad = sharedData.getRad();
                System.out.println("BT: " + rad*rad);
            }
        }
        
        System.out.println("T2 stop");
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }

}


#ThreadOne.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

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

/**
 *
 * @author Diep.Tran
 */
public class ThreadOne extends Thread{
    SharedData sharedData;

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


#Test02.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

/**
 *
 * @author Diep.Tran
 */
public class Test02 {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
        ThreadOne t1 = new ThreadOne(sharedData);
        ThreadTwo t2 = new ThreadTwo(sharedData);
        
        t1.start();
        t2.start();
    }
}


#SharedData.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson05;

/**
 *
 * @author Diep.Tran
 */
public class SharedData {
    int rad;
    int x;
    
    public synchronized void addMore(int delta) {
        System.out.println("x = " + x + ", delta: " + delta);
        x+=delta;
        System.out.println("x = " + x);
    }

    public int getRad() {
        return rad;
    }

    public void setRad(int rad) {
        this.rad = rad;
    }
}


Tags:

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

5

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