By GokiSoft.com| 15:29 19/07/2023|
Java Advanced

MultiThread - Synchronized trong Java - Đồng bộ 3 threads - Sinh số ngẫu nhiên, bình phương, và chia hết BT1102

Viết chương trình sau

Thread1 : Làm nhiệm vụ sinh ngẫu nhiên các số từ 1-100

- Nếu số ngẫu nhiên chia hết cho 3 thì đẩy sang Thread 2 : Thực hiện in ra bình phương số đó

- Trường hợp khác thì đẩy sang Thread 3 : Thực hiện kiểm ra xem số đó có chia hết cho 4 không và in ra thông báo (chia hết cho 4 hoặc ko)

- Nếu tổng các số sinh ngẫu nhiên trong Thread 1 >= 200 thì dừng tất cả các thread.

Thực hiện đồng bộ 3 thread (Yêu cầu : Thread 1 sinh xong -> đợi cho 2 thread 2 và 3 thực hiện xong mới sinh tiếp, Thread 2, 3 đợi cho Thread 1 sinh số ngẫu nhiên mới thì mới thực hiện yêu cầu)

Liên kết rút gọn:

https://gokisoft.com/1102

Bình luận

avatar
NguyenHuuThanh [T1907A]
2020-04-01 10:02:41



/*
 * 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 multithreadbt301;

/**
 *
 * @author abc
 */
public class Multithreadbt301 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        SharedData sharedData = new SharedData();
        
        Thread1 thread1 = new Thread1(sharedData);
        Thread2 thread2 = new Thread2(sharedData);
        Thread3 thread3 = new Thread3(sharedData);
        
        thread1.start();
        thread2.start();
        thread3.start();
    }
    
}
/*
 * 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 multithreadbt301;

/**
 *
 * @author abc
 */
public class SharedData {
    int rad;
    int total;
    // index = 1,2,3
    // index = 1 thi thread1 dc chay 2,3 wait or smth
    
    int index = 1;
    
    public SharedData()
    {
        total = 0;
        index = 1;
    }

    public int getRad() {
        return rad;
    }

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

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
    
    public synchronized void plus(int value)
    {
        total += value ;
    }
    
    public synchronized boolean checkAvailable()
    {
        return total < 2000;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
    
    
}

/*
 * 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 multithreadbt301;

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

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

    public Thread1(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run()
    {
        try {
            Thread.sleep(200); // t2 va t3 vao wait
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        Random random = new Random();
        
        while (sharedData.checkAvailable())
        {
            synchronized(sharedData)
            {
            int rad = random.nextInt(100) + 1;
            sharedData.setRad(rad);
            sharedData.plus(rad);
            System.out.println("T1 :" + rad);
            
            //thiet lap luong dc phep chay
            
            if (rad %3 == 0)
            {
                sharedData.setIndex(2);
                
            }
            else if (rad % 2 == 0)
            {
                sharedData.setIndex(3);
            }
            
            else
            {
                sharedData.setIndex(3);
            }
            // sync thread
            
            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();
        }
    }
    
    
}
/*
 * 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 multithreadbt301;

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

/**
 *
 * @author abc
 */
public class Thread2 extends Thread {
    SharedData sharedData;

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

    @Override
    public void run()
    {
        while (sharedData.checkAvailable())
        {
            
            synchronized(sharedData)
            {
                sharedData.notifyAll();
            try {
                while(sharedData.getIndex() != 2 && sharedData.checkAvailable())
                {
                    sharedData.wait();
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
            }
                
                int rad = sharedData.getRad();
            if (rad % 3 == 0)
            {
                rad *= rad;
                System.out.println("T2 : " + rad);
            }
             sharedData.setIndex(1);
            }
        }
        System.out.println("T2 : 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 multithreadbt301;

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

/**
 *
 * @author abc
 */
public class Thread3 extends Thread {
    SharedData sharedData;

    public Thread3(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run()
    {
        while (sharedData.checkAvailable())
        {
            
            
            
           synchronized(sharedData)
           {
               sharedData.notifyAll();
            try {
                while(sharedData.getIndex() != 3 && sharedData.checkAvailable())
                {
                    sharedData.wait();
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
            }
               
               
                int rad = sharedData.getRad();
            
            if (rad % 2 == 0)
            {
                if (rad % 4 == 0)
                {
                    System.out.println("So ngau nhien chia het cho 4 ");
                    
                }
                else
                {
                    System.out.println("So ngau nhien khong chia het cho4 ");
                }
                
                
            }
            else
            {
                System.out.println("So le");
            }
            sharedData.setIndex(1);
           }
            
            
        }
         System.out.println("T3 : Stop:");
         synchronized(sharedData)
        {
            sharedData.notifyAll();
        }
        
    }
   
}


avatar
Đỗ Văn Huấn [T1907A]
2020-03-31 13:25:44



package java2_Advanced.BaiTapNgay27_3_2020.DongBo3Thread;


public class Main {
    public static void main(String[] args) {

        ShareData shareData = new ShareData();

        IntRandom intRandom = new IntRandom(shareData);
        Sqr sqr = new Sqr(shareData);
        Divide divide = new Divide(shareData);


        intRandom.start();
        sqr.start();
        divide.start();


    }
}



package java2_Advanced.BaiTapNgay27_3_2020.DongBo3Thread;

public class ShareData {
    int rad;
    int tong;
    int indext;
    public ShareData() {
        tong = 0;
        indext = 1;
    }

    public int getIndext() {
        return indext;
    }

    public void setIndext(int indext) {
        this.indext = indext;
    }


    public void setTong(int tong) {
        this.tong = tong;
    }

    public int getTong() {
        return tong;
    }


    public int getRad() {
        return rad;
    }

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

    public synchronized void tong(int value) {
        tong += value;
    }

    public synchronized boolean checkTong() {
        if (tong >= 200) {
            return false;
        }
        return true;
    }

}



package java2_Advanced.BaiTapNgay27_3_2020.DongBo3Thread;


import java.util.Random;

public class IntRandom extends Thread {
    ShareData shareData;


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

    @Override
    public void run() {
        Random random = new Random();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (shareData.checkTong()) {
            synchronized (shareData) {
                int rad = random.nextInt(100) + 1;
                shareData.setRad(rad);
                System.out.println("Rad: " + rad);
                shareData.tong(rad);

                if (rad % 3 == 0) {                  // nếu rad chia hết cho 3 thì luồng 2 đc chạy và luồng 3 k đc chạy
                    shareData.setIndext(2);
                } else {                              // nếu rad k chia hết cho 3 thì luồng 3 đc chạy
                    shareData.setIndext(3);
                }

                shareData.notifyAll();
                try {
                    shareData.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        synchronized (shareData) {
            shareData.notifyAll();
        }
    }
}



package java2_Advanced.BaiTapNgay27_3_2020.DongBo3Thread;

public class Sqr extends Thread {
    ShareData shareData;

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

    @Override
    public void run() {
        while (shareData.checkTong()) {

            synchronized (shareData) {
                shareData.notifyAll();
                try {
                    while (shareData.getIndext() != 2 && shareData.checkTong()) {
                        shareData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                int rad = shareData.getRad();
                if (rad % 3 == 0) {
                    rad *= rad;
                    System.out.println("Sqr: " + rad);
                } else {
                    System.out.println(rad + " khong chia het cho 3.");
                }
                System.out.println("tong la: " + shareData.getTong());

                shareData.setIndext(1);          // chạy lại luồng 1
            }
        }
        synchronized (shareData) {
            shareData.notifyAll();
        }
    }
}



package java2_Advanced.BaiTapNgay27_3_2020.DongBo3Thread;

public class Divide extends Thread {
    ShareData shareData;

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

    @Override
    public void run() {

        while (shareData.checkTong()) {
            synchronized (shareData) {
                shareData.notifyAll();
                try {
                    while (shareData.getIndext() != 3 && shareData.checkTong() ) {
                        shareData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int rad = shareData.getRad();
                if (rad % 2 == 0) {
                    if (rad % 4 == 4) {
                        System.out.println(rad + " chia het cho 4.");
                    } else {
                        System.out.println(rad + " khong chia het cho 4.");
                    }
                } else {
                    System.out.println(rad + " khong chia het cho 2");
                }
                System.out.println("tong la: " + shareData.getTong());
                shareData.setIndext(1);             // chạy lại luồng 1
            }

        }
        synchronized (shareData) {
            shareData.notifyAll();
        }
    }
}