By GokiSoft.com| 09:24 16/09/2021|
Java Advanced

[Share Code] Bài toán đa luồng (MultiThreading in java) đọc File trong Java - C2009G

Bài toán đa luồng (MultiThreading in java) đọc File trong Java


#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 lesson07.bt1105;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        //randomNumberFile();
        ThreadOne t1 = new ThreadOne();
        ThreadTwo t2 = new ThreadTwo();
        ThreadThree t3 = new ThreadThree();
        
        t1.start();
        t2.start();
        t3.start();
    }
    
    static void randomNumberFile() {
        FileOutputStream fos = null;
        Random random = new Random();
        
        try {
            fos = new FileOutputStream("numbers.txt");
            
            int n = random.nextInt(90) + 10;
            byte[] b = (n + "\n").getBytes();
            fos.write(b);
            
            for (int i = 0; i < n; i++) {
                int num = random.nextInt(499) + 1;
                b = (num + "\n").getBytes();
                fos.write(b);
            }
            System.out.println("Hoan thanh tao numbers.txt");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


#SharedData.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 lesson07.bt1105;

/**
 * singleton
 * @author Diep.Tran
 */
public class SharedData {
    public static final int THREAD_1 = 1;
    public static final int THREAD_2 = 2;
    public static final int THREAD_3 = 3;
    
    int num;
    boolean live = true;
    int currentThread = THREAD_1;
    
    private static SharedData instance = null;
    
    private SharedData() {
    }
    
    public synchronized static SharedData getInstance() {
        if(instance == null) {
            instance = new SharedData();
        }
        return instance;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public boolean isLive() {
        return live;
    }

    public void setLive(boolean live) {
        this.live = live;
    }

    public int getCurrentThread() {
        return currentThread;
    }

    public void setCurrentThread(int currentThread) {
        this.currentThread = currentThread;
    }
}


#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 lesson07.bt1105;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class ThreadOne extends Thread{
    SharedData sharedData;
    int threadId = SharedData.THREAD_1;
    
    public ThreadOne() {
        sharedData = SharedData.getInstance();
    }

    @Override
    public void run() {
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader("numbers.txt");
            bufferedReader = new BufferedReader(reader);
            
            String line;
            bufferedReader.readLine();
            while((line = bufferedReader.readLine()) != null) {
                synchronized(sharedData) {
                    int num = Integer.parseInt(line);
                    System.out.println(num);
                    sharedData.setNum(num);

                    if(num % 2 == 0) {
                        //Chuyen sang cho Thread 2 thuc hien
                        sharedData.setCurrentThread(SharedData.THREAD_2);
                    } else {
                        // Chuyen sang cho Thread 3 thuc hien
                        sharedData.setCurrentThread(SharedData.THREAD_3);
                    }
                    sharedData.notifyAll();
                    while(sharedData.getCurrentThread() != threadId) {
                        sharedData.wait();
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        sharedData.setLive(false);
        
        System.out.println("T1 stop");
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
}


#ThreadThree.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 lesson07.bt1105;

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

/**
 *
 * @author Diep.Tran
 */
public class ThreadThree extends Thread{
    SharedData sharedData;
    int threadId = SharedData.THREAD_3;
    
    public ThreadThree() {
        sharedData = SharedData.getInstance();
    }

    @Override
    public void run() {
        while(sharedData.isLive()) {
            synchronized(sharedData) {
                sharedData.notifyAll();
                while(sharedData.isLive() && sharedData.getCurrentThread() != threadId) {
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadTwo.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if(!sharedData.isLive()) {
                    break;
                }
                
                int num = sharedData.getNum();
                System.out.println("T3: " + num * num);
                
                sharedData.setCurrentThread(SharedData.THREAD_1);
            }
        }
        
        System.out.println("T3 stop");
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
    
}


#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 lesson07.bt1105;

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

/**
 *
 * @author Diep.Tran
 */
public class ThreadTwo extends Thread{
    SharedData sharedData;
    int threadId = SharedData.THREAD_2;
    
    public ThreadTwo() {
        sharedData = SharedData.getInstance();
    }

    @Override
    public void run() {
        while(sharedData.isLive()) {
            synchronized(sharedData) {
                sharedData.notifyAll();
                while(sharedData.isLive() && sharedData.getCurrentThread() != threadId) {
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadTwo.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if(!sharedData.isLive()) {
                    break;
                }

                int num = sharedData.getNum();
            
                System.out.print("T2: 1");
                for (int i = 2; i < num; i++) {
                    if(num % i == 0) {
                        System.out.print("," + i);
                    }
                }
                System.out.println("");
                
                sharedData.setCurrentThread(SharedData.THREAD_1);
            }
        }
        
        System.out.println("T2 stop");
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
    
}


Tags:

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

5

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