By GokiSoft.com| 15:42 17/07/2023|
Java Advanced

Tao tác dữ liệu lên Shared Object sử dụng MultiThreading trong java

Viết chương trình thực hiện yêu cầu sau

- Thiết kế 1 class SharedData có chứa biến nguyên total

- Thiết kế thread 1 thực hiện sinh ngẫu nhiên các số từ 0 - 100 -> Sau đó thêm số ngẫu nhiên này vào biến total trong SharedData (Ví dụ : Số ngẫu nhiên rad khi đó total = total + rad)

- Thiết kế thread 2 thực hiện sinh ngẫu nhiên các số từ -100 - 0 -> Sau đó thêm số ngẫu nhiên này vào biến total trong SharedData (Ví dụ : Số ngẫu nhiên rad khi đó total = total + rad)

Khi giá trij total của SharedData <= -100 hoặc >= 100 thì thực hiện dừng 2 thread trên.

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

5

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

Trần Thị Khánh Huyền [T2008A]
Trần Thị Khánh Huyền

2021-03-19 09:17:23



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

/**
 *
 * @author Admin
 */
public class Main {
   public static void main(String[] args) {
       SharedData sharedData = new SharedData();
       
       Thread1 t1 = new Thread1(sharedData);
       Thread2 t2 = new Thread2(sharedData);
       
       t1.start();
       t2.start();
   }
}



NguyenHuuThanh [T1907A]
NguyenHuuThanh

2020-04-02 23:46:24



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

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

    /**
     * @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);
        
        thread1.start();
        thread2.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 multithreadbt6;

import java.util.Random;

/**
 *
 * @author abc
 */
public class SharedData {
    int total;
    int rad;

    public int getRad() {
        return rad;
    }

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

    public SharedData(int total) {
        this.total = total;
    }

    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()
    {
        if (  total <= -100 || total >= 100 )
        {
            return false;
        }
        else return true;
    }
    
    public static int getRandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.ints(min,(max+1)).findFirst().getAsInt();
    }
    
}
/*
 * 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 multithreadbt6;

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()
    {
        Random random = new Random();
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        synchronized(sharedData)
        {
            
            while(sharedData.checkAvailable())
        {
            int rad = random.nextInt(100);
            sharedData.setRad(rad);
            sharedData.plus(rad);
            
            System.out.println("rad :" + 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();
        }
    }
    
    
}
/*
 * 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 multithreadbt6;

import java.util.Random;
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()
    {
        synchronized(sharedData)
        {
            sharedData.notifyAll();
            try {
                sharedData.wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
            }
            while(sharedData.checkAvailable())
        {
            Random random = new Random();
            int rad = sharedData.getRandomNumber(-100 , 0);
            sharedData.setRad(rad);
            sharedData.plus(rad);
            
            System.out.println("Rad :" + rad);
        }
        }
        
        System.out.println("T2 : stop");
        synchronized(sharedData)
        {
            sharedData.notifyAll();
        }
    }
    
}



Đỗ Văn Huấn [T1907A]
Đỗ Văn Huấn

2020-03-31 14:58:49



package java2_Advanced.BaiTapNgay30_3_2020.ThaoTacDuLieuTren_SharedObject;

public class Data {
    int total;

    public Data() {
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public synchronized void tinhTotal( int rad){
        total += rad;
    }
    public synchronized boolean checkTotal(){
        if( -100 >= total || total >= 100){
            return false;
        }
        return true;
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.ThaoTacDuLieuTren_SharedObject;

import java.util.Random;

public class Thread1 extends Thread {
    Data data;

    public Thread1(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        Random random = new Random();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (data.checkTotal()) {
            synchronized (data){
                int rad = random.nextInt(99) + 1;
                System.out.println(" rad 1: " + rad);
                data.tinhTotal(rad);

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

        }
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.ThaoTacDuLieuTren_SharedObject;

import java.util.Random;

public class Thread2 extends Thread {
    Data data;

    public Thread2(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        Random random = new Random();
        while (data.checkTotal()) {
            synchronized (data){
                data.notifyAll();
                try {
                    data.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int rad2 = random.nextInt(100) -100;
                System.out.println(" rad 2: " + rad2);
                data.tinhTotal(rad2);
            }
        }
        synchronized (data){
            data.notifyAll();
        }
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.ThaoTacDuLieuTren_SharedObject;

public class Test {
    public static void main(String[] args) {
        Data data = new Data();
        Thread1 thread1 = new Thread1(data);
        Thread2 thread2 = new Thread2(data);

        thread1.start();
        thread2.start();
    }
}



thienphu [T1907A]
thienphu

2020-03-31 02:40:26



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

/**
 *
 * @author Thien Phu
 */
public class DataShare {

    int total;

    public DataShare() {
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getTotal() {
        return total;
    }

    public void tongTotal(int random) {
        total += random;
        System.out.println("Total sau khi cong t2: " + total);
    }

    public synchronized boolean checkStatus() {
        if (total >= 100 || total <= -100) {
            
            return false;
        }
        return true;
    }
}



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

/**
 *
 * @author Thien Phu
 */
/*
 * 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.
 */
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Thien Phu
 */
public class Thread1 extends Thread {

    DataShare dataShare;

    public Thread1(DataShare dataShare) {
        this.dataShare = dataShare;
    }
//sinh so ngau nhien

    @Override
    public void run() {

        while (dataShare.checkStatus()) {
            synchronized (dataShare) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
                Random r = new Random();
                int random = r.nextInt(101);
                dataShare.setTotal(random);
                System.out.println("Random: " + dataShare.getTotal());
                dataShare.notifyAll();
                try {
                    dataShare.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        }
        synchronized(dataShare){
            System.out.println("Stop thread 1");
            stop();
        }

    }
}



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

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

/**
 *
 * @author Thien Phu
 */
public class Thread2 extends Thread {

    DataShare dataShare;

    public Thread2(DataShare dataShare) {
        this.dataShare = dataShare;
    }

    @Override
    public void run() {
        
        while (dataShare.checkStatus()) {
                synchronized (dataShare) {
                dataShare.notifyAll();
                try {
                    System.out.println("Dợi");
                    dataShare.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                Random r = new Random();
                int random = r.nextInt(101);
                System.out.println("Random 2: " + random);
                dataShare.tongTotal(random);
                
            }
        }
        System.out.println("Stop thread 2");
        synchronized(dataShare)
        {
            dataShare.notifyAll();
            stop();
        }
    }
}



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

/**
 *
 * @author Thien Phu
 */
public class Main {

    public static void main(String[] args) {
        DataShare dataShare = new DataShare();
        Thread1 t1 = new Thread1(dataShare);
        Thread2 t2 = new Thread2(dataShare);
        t2.start();
        t1.start();
    }
}



Trương Công Vinh [T1907A]
Trương Công Vinh

2020-03-30 15:10:13



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

/**
 *
 * @author DELL
 */
public class shareData {
    int total;
    int index = 1;

    public int getIndex() {
        return index;
    }

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

    public shareData() {
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
    public synchronized void total(int rad){
        total+=rad;
        
    }
    public synchronized boolean checkTotal(){
        if ((total >= 100) || ( total <=-100)) {
            return false;
        }return true;
    }
}



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

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

/**
 *
 * @author DELL
 */
public class thread1 extends Thread {

    shareData sharedata;

    public thread1(shareData sharedata) {
        this.sharedata = sharedata;
    }

    @Override
    public void run() {
        Random rad = new Random();
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        while (sharedata.checkTotal()) {
            synchronized (sharedata) {
               
                int n = rad.nextInt(101);
                sharedata.total(n);
                System.out.println("Thread 1 (" + n + ") - total : " + sharedata.getTotal());
                sharedata.setIndex(2);
                sharedata.notifyAll();
                try {
                    sharedata.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        
    }

}



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

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

/**
 *
 * @author DELL
 */
public class thread2 extends Thread {

    shareData sharedata;

    public thread2(shareData sharedata) {
        this.sharedata = sharedata;
    }

    @Override
    public void run() {
        Random rad = new Random();
        while (sharedata.checkTotal()) {
            synchronized (sharedata) {
                sharedata.notifyAll();
                try {
                    while (sharedata.getIndex()!=2 && sharedata.checkTotal()) {                        
                        sharedata.wait();
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                int n = -rad.nextInt(101);
                
                sharedata.total(n);
                System.out.println("Thread 2 (" + n + ") - total : " + sharedata.getTotal());
                sharedata.setIndex(1);
               sharedata.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 Thread2;

/**
 *
 * @author DELL
 */
public class main {
    public static void main(String[] args) {
        shareData sharedata = new shareData();
        thread1 t1 = new thread1(sharedata);
        thread2 t2 = new thread2(sharedata);
        t1.start();
        t2.start();
    }
}