By GokiSoft.com| 20:10 19/08/2021|
Java Advanced

[Share Code] Tìm hiểu đa luồng - Thread - Sync - wait/notifyAll trong Java - Lập trình Java



- Process (Tien trinh)
	- Thread (Luong)

PC (OS Win, Linux, MacOS, ...)
	Chrome -> process
	Sublime Text 3 -> process
	Show Slide -> process
	Netbean -> process
	...

	//Chay // -> 
	-> Xu ly tu -> 

CPU -> 1 core, 2 core, 4 core, 8 core ...
...
CPU -> 1 core

p1 -> p10
OS -> FIFO, LIFO, Round Robin

1s -> CPU -> 1 trieu

Phan mem (Game)
	- Chat				-> Thread -> T1
	- thao tac game		-> T2
	- nhan vat chat		-> T3
	- nghe nhac			-> T4
	- clip 				-> T5
	- tai du lieu 		-> T6
	...
	...
	5 Thread ...

Phan Tich
Main .....................
T1			 .............
T2         ...............
T3            ............

Main ........             ...................
T1			 .............
T2         ..................................
T3                        ...................

II) Xu ly da luong
data -> count
T1->T10: -> can thiep vao vung du lieu data +delta, -delta -> count: ???

SRO: Gio hoa qua: 24 thang

Dong bo Thread -> 
T1->10: queue -> xep hang -> T1 (xu ly xong) -> T2 -> ...

Gio hoa qua: 24 -> queue -> ...

Dong bo thread -> Data Error (Tien nong, tai chinh, so lieu, ...) -> ...

==================================================
T1:
	Sinh ngau nhien 1 so tu nhien tu 1->100

T2:
	Hien thi binh phuong so tu nhien dc sinh ra o T1
Yeu cau sync theo yeu cau sau
T1......(rad)            ...(rad)....                .....
T2.         ..(rad*rad)..            ...(rad*rad)....


Phan tich bai toan:
T2      ...(wait)                                 wake(sync)..get(rad)..BT..display..flag..sync..continue..notifyAll....wait
T1(sync)         ...(rad)..set..display..notifyAll....(wait)                                                       wake(sync).........


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 java2.lesson4;

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

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

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

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

        new Thread(() -> {
            System.out.println("Test 2");
            for (int i = 0; i < 20; i++) {
                try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                System.out.println("T2 -> " + i);
            }
        }).start();//Main + T2 (co the dang chay)
        t1.start();//Main + T2 (Dang chay hoac da ket thuc) + T1 (Co the dang chay)
        
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        t3.start();
        t3.stop();
        t3 = new CustomThread();
        t3.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 java2.lesson4;

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

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

    @Override
    public void run() {
        System.out.println(getName() + " -> start");

        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(getName() + " -> " + i);
        }
    }

}

Phần 2:


#ChangeThread.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 java2.lesson4;

/**
 *
 * @author Diep.Tran
 */
public class ChangeThread extends Thread{
    ShareData shareData;

    public ChangeThread(ShareData shareData) {
        this.shareData = shareData;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            shareData.change(1);
        }
    }
}


#Test.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 java2.lesson4;

/**
 *
 * @author Diep.Tran
 */
public class Test {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        //Xu ly tuan tu -> ko gap van de.
        /**for (int i = 0; i < 10; i++) {
            shareData.change(1);
        }*/
        
        //Xu ly da Thread
        ChangeThread t1 = new ChangeThread(shareData);
        ChangeThread t2 = new ChangeThread(shareData);
        ChangeThread t3 = new ChangeThread(shareData);
        ChangeThread t4 = new ChangeThread(shareData);
        ChangeThread t5 = new ChangeThread(shareData);
        ChangeThread t6 = new ChangeThread(shareData);
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
    }
}


#ShareData.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 java2.lesson4;

/**
 *
 * @author Diep.Tran
 */
public class ShareData {
    int count = 0;
    int rad;
    
    public synchronized void change(int delta) {
        System.out.println("F ->" + count + ", delta -> " + delta);
        count += delta;
        System.out.println("A -> " + count);
        //Trong 1 function -> ko gioi han so lenh chay -> ...
    }

    public int getRad() {
        return rad;
    }

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

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 java2.lesson4;

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

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

    ShareData shareData;

    public ThreadTwo(ShareData shareData) {
        this.shareData = shareData;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (shareData) {
                try {
                    shareData.notifyAll();
                    shareData.wait();//Nha flag -> de thread sync -> chay vao -> wait -> sync
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadTwo.class.getName()).log(Level.SEVERE, null, ex);
                }
                int rad = shareData.getRad();
                System.out.println("BT: " + rad * rad);
            }
        }
        System.out.println("T2 stop");
        synchronized(shareData) {
            shareData.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 java2.lesson4;

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

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

    ShareData shareData;

    public ThreadOne(ShareData shareData) {
        this.shareData = shareData;
    }

    @Override
    public void run() {
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            synchronized (shareData) {
                int rad = random.nextInt(100);
                shareData.setRad(rad);
                System.out.println(rad);

                try {
                    shareData.notifyAll();
                    shareData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        System.out.println("T1 stop");
        synchronized(shareData) {
            shareData.notifyAll();
        }
    }
}


#ShareData.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 java2.lesson4;

/**
 *
 * @author Diep.Tran
 */
public class ShareData {
    int count = 0;
    int rad;
    
    public synchronized void change(int delta) {
        System.out.println("F ->" + count + ", delta -> " + delta);
        count += delta;
        System.out.println("A -> " + count);
        //Trong 1 function -> ko gioi han so lenh chay -> ...
    }

    public int getRad() {
        return rad;
    }

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


#Test2.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 java2.lesson4;

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


Tags:

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

5

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