By GokiSoft.com| 16:58 27/03/2020|
Java Advanced

Share Code - Thread - MultiThread - Synchonized wait notify notifyAll trong java



- Synchonized
- wait, notify, notifyAll => run

Bài tập
- T1 >> sinh ngẫu nhiên 1 số tự nhiên từ 1-100
- T2 >> hiển thị bình phương số đã được sinh từ T1
1. Tạo 2 thread thực hiện yêu cầu trên
2. Đồng bộ luồng
T1 thực hiện > rad > T1 đợi T2 > hiển thị bình phương số rad > in ra màn hình > T2 wait > T1 chạy => vòng tròn như trên
3. Sinh ngẫu nhiên 10 sô => stop 2 luồng.

=> Phân tích
T1 > rad => lưu trữ
T2 > lấy số rad => hiển thị
=> DataMgr => SharedData

= Giải thích
T1 => chạy tới >> synchronized >> chiếm quyền xử lý đầu tiên
T2 => tới synchronized sau => đợi (queue)

T1 > sinh số ngẫu nhiên => Shared Data => hiển thị => gọi tới notifyAll (wait) => T2 vẫn ở trạng chờ (queue) => T1 => wait
T2 => được chạy vào => T2 => T2 notifyAll => T1 sẵn sàng >> T2 vào wait >> T1 được chạy >> ...



/*
 * 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 java2.lession4;

/**
 *
 * @author Diep.Tran
 */
public class SharedData {
    int rad;

    public SharedData() {
    }

    public int getRad() {
        return rad;
    }

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



/*
 * 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 java2.lession4;

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

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

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

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadRandom.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Random random = new Random();
        
        for (int i = 0; i < 10; i++) {
//            System.out.println("T1 >> " + i);
            synchronized(sharedData) {
                int rad = random.nextInt(100) + 1;
                sharedData.setRad(rad);
                System.out.println("Rad : " + rad);
                //trien khai them
                //wait => T2 chay.
                sharedData.notifyAll();
                try {
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadRandom.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        System.out.println("T1 Stop");
        //stop
        //stop
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
}



/*
 * 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 java2.lession4;

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

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

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

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
//            System.out.println("T2 >> " + i);
            synchronized(sharedData) {
                try {
                    sharedData.notifyAll();
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadSquare.class.getName()).log(Level.SEVERE, null, ex);
                }
                int rad = sharedData.getRad();
                rad *= rad;
                System.out.println("PT: " + rad);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadRandom.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println("T2 Stop");
        //stop
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
    
    
}



/*
 * 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 java2.lession4;

/**
 *
 * @author Diep.Tran
 */
public class Test2 {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
        ThreadRandom threadRandom = new ThreadRandom(sharedData);
        ThreadSquare threadSquare = new ThreadSquare(sharedData);
        
        threadSquare.start();
        threadRandom.start();
    }
}


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

5

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