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

MultiThread - Sinh số ngẫu nhiên và hiển thị bình phương số ngẫu nhiên & Synchronized trong Java

Viết chương trình làm task vu như sau

- Thread thứ nhất thực hiện sinh ngẫu nhiên các số tự nhiêu từ 1 tới 20 - Dừng 2s và chạy vô tận

- Thread thứ 2 thực hiện hiển thị bình phương các số được sinh ra từ Thread 1- Dừng 1s và chạy vô tận

- Thực hiện đồng bộ 2 Thread trên (T1 thực hiện sinh ngẫu nhiên > T2 in ra bình phương > T1 tiếp tục sinh > T2 in ra bình phương > ...)

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

5

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

vuong huu phu [T2008A]
vuong huu phu

2021-03-18 03:55:34



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

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

/**
 *
 * @author Admin
 */
public class Thread1 extends Thread {
    S_dt s;
    public Thread1(S_dt s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        Random rd = new Random();
        for (int i = 0; i >-1; i++) {
            synchronized(s){
                    int n = rd.nextInt(20);
                    s.setR(n);
                    System.out.println("T1 = " + n);
                    s.notifyAll();
                try {
                    sleep(2000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
                s.notifyAll();
                try {    
                    s.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
        }}
    }

}



vuong huu phu [T2008A]
vuong huu phu

2021-03-18 03:55:11



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

/**
 *
 * @author Admin
 */
public class Test {

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



Nguyễn Tiến Đạt [T2008A]
Nguyễn Tiến Đạt

2021-03-17 14:36:08


#Data.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.MultiThreadBinhPhuong;

/**
 *
 * @author MyPC
 */
public class Data {
    int random;

    public int getRandom() {
        return random;
    }

    public void setRandom(int random) {
        this.random = random;
    }
    
    
}


#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.MultiThreadBinhPhuong;

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


#Thread1.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.MultiThreadBinhPhuong;

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

/**
 *
 * @author MyPC
 */
public class Thread1 extends Thread{
    Data data;

    public Thread1(Data data) {
        this.data = data;
    }
    
    @Override
    public void run() {
        try {
            sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        Random random = new Random();
        while(true){
            synchronized(data){
                int rad = random.nextInt(21);
                data.setRandom(rad);
                System.out.println("Rad: " + rad);
                
                data.notifyAll();
                
                try {
                    data.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }  
        }
    }
    
}


#Thread2.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.MultiThreadBinhPhuong;

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

/**
 *
 * @author MyPC
 */
public class Thread2 extends Thread{
    Data data;

    public Thread2(Data data) {
        this.data = data;
    }
    
    @Override
    public void run() {
        while(true){
            synchronized(data){
                data.notifyAll();
                try {
                    data.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                int random = data.getRandom();
                System.out.println("Square of random: " + random*random);
            }
        }
    }
    
}



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

2021-03-17 10:06:08



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

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

/**
 *
 * @author Admin
 */
public class Thread2 extends Thread {
    SharedData sharedData;
    
    public Thread2(SharedData sharedData) {
       this.sharedData=sharedData;
    }
    @Override
    public void run() {
       for ( ;; ){
         synchronized(sharedData){
             sharedData.notify();
             try {
                 sharedData.wait();
             } catch (InterruptedException ex) {
                 Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
             }
             int rad = sharedData.getRad();
             rad*=rad;
             System.out.println("BP: "+rad);
         }  
       }
    }
    
}



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

2021-03-17 10:05:38



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

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

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

    public Thread1(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Random random = new Random();
        for ( ;; ){
           synchronized(sharedData){
               int rad= random.nextInt();
               sharedData.setRad(rad);
               System.out.println("Rad: "+rad);
               
               sharedData.notifyAll();
               
               try {
                   sharedData.wait();
               } catch (InterruptedException ex) {
                   Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
               }
               
           } 
        } 
    }
    
}



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

2021-03-17 10:05:02



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

/**
 *
 * @author Admin
 */
public class SharedData {
    int rad;

    public int getRad() {
        return rad;
    }

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



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

2021-03-17 10:04:28



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


/**
 *
 * @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-03-31 21:10:06



/*
 * 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 bt.synchronize;

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

    /**
     * @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 bt.synchronize;

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();
        for ( ;; )
        {
            synchronized(sharedData)
            {
                int rad = random.nextInt(20) + 1;
            sharedData.setRad(rad);
            System.out.println("random" + rad);
            try {
                Thread1.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            sharedData.notifyAll();
                try {
                    sharedData.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 bt.synchronize;

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()
    {
        for(;;)
        {
            synchronized(sharedData)
            {
               
                try {
                    sharedData.notifyAll();
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                int rad = sharedData.getRad();
            rad *= rad;
            System.out.println("BP :" + rad);
            try {
                Thread2.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread2.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 bt.synchronize;

/**
 *
 * @author abc
 */
public class SharedData {
    int rad;
    
    public SharedData()
    {
        
    }

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

    public int getRad() {
        return rad;
    }
    
    
}



thienphu [T1907A]
thienphu

2020-03-31 01:23: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 MultiThread1;

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

    int random;

    public DataShared() {
    }

    public void setRandom(int random) {
        this.random = random;
    }

    public int getRandom() {
        return random;
    }

}



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

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

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

    DataShared dataShared;

    public Thread1Random(DataShared dataShared) {
        this.dataShared = dataShared;
    }
//sinh so ngau nhien

    @Override
    public void run() {

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread1Random.class.getName()).log(Level.SEVERE, null, ex);
            }
            Random r = new Random();
            synchronized (dataShared) {
                int random = r.nextInt(21);
                dataShared.setRandom(random);
                System.out.println("Random: " + random);
                dataShared.notifyAll(); // đánh thức tất cả các thằng dang ở trạng thái đợi vào chạy
                try {
                    dataShared.wait();// chuyển sang trạng thái wait()xem thằng kia chạy
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1Random.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 MultiThread1;

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

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

    DataShared dataShared;

    public Thread2Square(DataShared dataShared) {
        this.dataShared = dataShared;
    }

    @Override
    public void run() {
        while (true) {

            synchronized (dataShared) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2Square.class.getName()).log(Level.SEVERE, null, ex);
                }
                dataShared.notifyAll();//dánh thức những thằng đang wait về chạy
                try {
                    dataShared.wait();// chuyển trạng thái của Thread2 sang trạng thái wait
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2Square.class.getName()).log(Level.SEVERE, null, ex);
                }
                int square = dataShared.getRandom();
                square *= square;
                System.out.println("Square: " + square);
            }
        }
    }

}



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

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

    public static void main(String[] args) {
        DataShared dataShared = new DataShared();
        Thread1Random t1 = new Thread1Random(dataShared);
        Thread2Square t2 = new Thread2Square(dataShared);
        t1.start();
        t2.start();

    }
}



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

2020-03-28 14:24:00



package java2_Advanced.BaiTapNgay27_3_2020.MultiThread_SynchronizedTrongJava;

public class ShareData {
    int rad;

    public ShareData() {
    }

    public int getRad() {
        return rad;
    }

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



package java2_Advanced.BaiTapNgay27_3_2020.MultiThread_SynchronizedTrongJava;

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

public class ThreadRandom extends Thread {
    ShareData shareData;

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

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Random random = new Random();

        for (; ; ) {
            synchronized (shareData) {
                int rad = random.nextInt(20) + 1;
                shareData.setRad(rad);
                System.out.println("Rad : " + rad);

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




package java2_Advanced.BaiTapNgay27_3_2020.MultiThread_SynchronizedTrongJava;

public class ThreadSqr extends Thread {
    ShareData shareData;

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

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

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

                int rad = shareData.getRad();
                rad *= rad;
                System.out.println("Square: " + rad);
                System.out.println("");

            }
        }
    }
}



package java2_Advanced.BaiTapNgay27_3_2020.MultiThread_SynchronizedTrongJava;

public class Test {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        ThreadRandom threadRandom = new ThreadRandom(shareData);
        ThreadSqr threadSqr = new ThreadSqr(shareData);

        threadRandom.start();
        threadSqr.start();

    }
}