By GokiSoft.com| 14:57 01/04/2020|
Java Advanced

Share Code - Hướng dẫn chữa bài >> Bài tập ôn luyện tổng hợp File, OOP, Thread trong java

Hướng dẫn chữa bài >> Bài tập ôn luyện tổng hợp File, OOP, Thread trong 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.lession6;

import java.io.Serializable;
import java.util.regex.Pattern;

/**
 *
 * @author Diep.Tran
 */
public class Student implements Serializable{
    String rollNo;

    public Student() {
    }

    public Student(String rollNo) {
        this.rollNo = rollNo;
    }

    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
    
    public static boolean checkValidRollNo(String rollNo) {
        String pattern = "[CTN][0-9]{4}[G-M][V]?[0-9]{4}";
        boolean matches = Pattern.matches(pattern, rollNo);
        return matches;
    }
}



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

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @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;
    
    List<Student> validRollNumber;
    List<String> unvalidRollNumber;
    int currentThread;
    boolean alive;

    public SharedData() {
        validRollNumber = new ArrayList<>();
        unvalidRollNumber = new ArrayList<>();
        currentThread = 0;
        alive = true;
    }

    public List<Student> getValidRollNumber() {
        return validRollNumber;
    }

    public void setValidRollNumber(List<Student> validRollNumber) {
        this.validRollNumber = validRollNumber;
    }

    public List<String> getUnvalidRollNumber() {
        return unvalidRollNumber;
    }

    public void setUnvalidRollNumber(List<String> unvalidRollNumber) {
        this.unvalidRollNumber = unvalidRollNumber;
    }

    public int getCurrentThread() {
        return currentThread;
    }

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

    public boolean isAlive() {
        return alive;
    }

    public void setAlive(boolean alive) {
        this.alive = alive;
    }
}



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

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 Thread1 extends Thread{
    SharedData sharedData;

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

    @Override
    public void run() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        FileReader reader = null;
        BufferedReader bReader = null;
        
        try {
            reader = new FileReader("student.txt");
            bReader = new BufferedReader(reader);
            String line = null;
            
            while(sharedData.isAlive()) {
                //sync du lieu tu day
                synchronized(sharedData) {
                    line = bReader.readLine();
                    if(line == null) {
                        sharedData.setAlive(false);
                        break;
                    }
                    
                    boolean isValid = Student.checkValidRollNo(line);
                    if(isValid) {
                        Student std = new Student(line);
                        sharedData.getValidRollNumber().add(std);
                        sharedData.setCurrentThread(SharedData.THREAD_2);
                    } else {
                        sharedData.getUnvalidRollNumber().add(line);
                        sharedData.setCurrentThread(SharedData.THREAD_3);
                    }
                    
                    sharedData.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(bReader != null) {
                try {
                    bReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //ket thuc doc du lieu tu file student.txt
        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 java2.lession6;

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

/**
 *
 * @author Diep.Tran
 */
public class Thread2 extends Thread{
    SharedData sharedData;

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

    @Override
    public void run() {
        while(sharedData.isAlive()) {
            synchronized(sharedData) {
                sharedData.notifyAll();
                try {
                    while(sharedData.getCurrentThread() != SharedData.THREAD_2 && sharedData.isAlive()) {
                        sharedData.wait();
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                int length = sharedData.getValidRollNumber().size();
                if(length > 0) {
                    Student std = sharedData.getValidRollNumber().get(length - 1);
                    System.out.println("Welcome student has roll no is: " + std.getRollNo());
                    System.out.println("Valid collection has length: " + length);
                    
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;
                    try {
                        //ghi vao file .dat
                        fos = new FileOutputStream(std.getRollNo() + ".dat");
                        oos = new ObjectOutputStream(fos);
                        
                        oos.writeObject(std);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        if(oos != null) {
                            try {
                                oos.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(fos != null) {
                            try {
                                fos.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                    
                } else {
                    System.out.println("Error!!!");
                }
                
                sharedData.setCurrentThread(SharedData.THREAD_1);
            }
        }
        //ket thuc doc du lieu tu file student.txt
        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 java2.lession6;

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

/**
 *
 * @author Diep.Tran
 */
public class Thread3 extends Thread{
    SharedData sharedData;

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

    @Override
    public void run() {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("unvalid.txt");
            
            while (sharedData.isAlive()) {                
                synchronized(sharedData) {
                    sharedData.notifyAll();
                    try {
                        while(sharedData.getCurrentThread() != SharedData.THREAD_3 && sharedData.isAlive()) {
                            sharedData.wait();
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                    int length = sharedData.getUnvalidRollNumber().size();
                    String rollNo = sharedData.getUnvalidRollNumber().get(length - 1);
                    
                    System.out.println("Unvalid roll number: " + rollNo);
                    
                    //ghi unvalid roll number vao file
                    rollNo += "\n";
                    byte[] b = rollNo.getBytes();
                    fos.write(b);
                    
                    //chuyen thread
                    sharedData.setCurrentThread(SharedData.THREAD_1);
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        //ket thuc thread 3
        
        //ket thuc doc du lieu tu file student.txt
        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 java2.lession6;

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


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

5

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