By GokiSoft.com| 15:29 09/11/2022|
Java Advanced

Bài tập ôn luyện tổng hợp File, OOP, Thread trong java

A.           Tạo Class Student .                                                             

a.    Có trường thuộc tính: String studRollNo.

b.    Xây dựng các phương thức get/set cho thuộc tính và hàm tạo có tham số để truyền giá trị cho thuộc tính trên

B.           Tạo ứng dụng đa luồng sử dụng cơ chế wait–notify làm công việc sau:

 

-      Thread1 :                                                                          

o   Sử dụng BufferedReader để mở file “students.txt”  

§  File “students.txt” lưu trữ roll number của các sinh viên, mỗi roll Trên 1 dòng.

§  Roll number hợp lệ có mẫu như sau:

·         abbbbdebbbb

·         Trong đó

o   a là khóa học, có giá trị hoặc là: ‘C’, ‘T’, ‘N’

o   b là số trong khoảng 0-9

o   d là giờ học của lớp, có giá trị hoặc là: ‘G’, ‘H’ , ‘I’, ‘K’, ‘L’, ‘M’

o   e là kiểu lớp học. e có thể không có giá trị hoặc chỉ có 1 giá trị là ‘V’

·         Ví dụ:

o   C1009H0001 là hợp lệ

o   T0812KV0002 là hợp lệ

o   TT0812KV0002 là không hợp lệ

o   C1009H00012 là không hợp lệ

o   C10030003 là không hợp lệ

o   C1103T004 là không hợp lệ

o   G1103T004 là không hợp lệ

§  Một roll hợp lệ được dùng để tạo ra 1 đối tượng sinh viên (sử dụng hàm tạo có tham số) và sau đó được add vào 1 collection tên là validRollNumber sử dụng generic là kiểu Student , Sau đó chuyển công việc qua Thread2.                       

§  Một roll không hợp lệ được add liên tiếp vào 1 collection tên là unvalidRollNumber có kiểu generic là String, Sau đó chuyển công việc qua Thread3.                                      

§  validRollNumber và unvalidRollNumber collection được khai báo trong Class SharedData được sử dụng trong ứng dụng đa luồng cho phép có thể thao tác đồng thời trên dữ liệu của chúng.

-      Thread2 :

Ngay lập tức sau khi có 1 sinh viên được add vào collection validRollNumber.

o   Thread2 lấy thông tin sinh viên vừa được add vào collection ra để hiển thị và có 1 dòng thông báo liền kề sau đó là độ dài hiện tại của collection validRollNumber.

§  Ví dụ                                                  

·         "Welcome student has roll number is :…"

·         “Valid collection has length :…”

o   Đồng thời Thread2 ghi đối tượng sinh viên này xuống file xxx.dat       

§  Trong đó: xxx là roll number của sinh viên.

·         Ví dụ: C1009H0001.dat hoặc T0812KV0002.dat

 

-      Thread3:

Ngay sau khi 1 roll number không hợp lệ được add vào collection unvalidRollNumber  .

o   Thread3 lấy nó ra và hiển thị dưới dạng:

§  "Unvalid roll number :…" 

o    Đồng thời ghi xuống file unvalid.txt , file unvalid.txt có nhiều dòng, mỗi dòng ghi một roll number không hợp lệ

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

5

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

TRẦN VĂN ĐIỆP [Teacher]
TRẦN VĂN ĐIỆP

2021-03-19 07:55:10


#Thread3.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 aptech.java2.bt1104;

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", true);

            while (true) {
                synchronized (sharedData) {
                    sharedData.notifyAll();
                    try {
                        while(sharedData.getCurrentThreadIndex() != SharedData.THREAD_3 && !sharedData.isIsStop()) {
                            sharedData.wait();
                        }
                        if(sharedData.isIsStop()) {
                            break;
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    String rollNo = sharedData.getUnvalidRollNoLast();
                    System.out.println("Unvalid roll number : " + rollNo);

                    byte[] b = rollNo.getBytes();
                    fos.write(b);
                
                    sharedData.setCurrentThreadIndex(SharedData.THREAD_1);
                }
            }
            
            sharedData.setIsStop(true);
            synchronized(sharedData) {
                sharedData.notifyAll();
            }
        } 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);
                }
            }
        }
    }
}


#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 aptech.java2.bt1104;

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(true) {
            synchronized(sharedData) {
                sharedData.notifyAll();
                try {
                    while(sharedData.getCurrentThreadIndex() != SharedData.THREAD_2 && !sharedData.isIsStop()) {
                        sharedData.wait();
                    }
                    
                    if(sharedData.isIsStop()) {
                        break;
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                Student std = sharedData.getValidStudentLast();
            
                System.out.println("Welcome student has roll number is : " + std.getStudRollNo());
                System.out.println("Valid collection has length : " + sharedData.getValidRollNumber().size());

                FileOutputStream fos = null;
                ObjectOutputStream oos = null;

                try {
                    fos = new FileOutputStream(std.getStudRollNo() + ".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(fos != null) {
                        try {
                            fos.close();
                        } catch (IOException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    if(oos != null) {
                        try {
                            oos.close();
                        } catch (IOException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
                
                sharedData.setCurrentThreadIndex(SharedData.THREAD_1);
            }
        }
        
        sharedData.setIsStop(true);
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
}


#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 aptech.java2.bt1104;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
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() {
        FileInputStream fis = null;
        InputStreamReader reader = null;
        BufferedReader bReader = null;
        
        try {
            fis = new FileInputStream("student.txt");
            reader = new InputStreamReader(fis);
            bReader = new BufferedReader(reader);
            
            String rollNo = null;
            
            while(true) {
                synchronized(sharedData) {
                    rollNo = bReader.readLine();
                    if(rollNo == null) break;
                    if(rollNo.isEmpty()) continue;

                    boolean valid = sharedData.addRollNo(rollNo);
                    if(valid) {
                        sharedData.setCurrentThreadIndex(SharedData.THREAD_2);
                    } else {
                        sharedData.setCurrentThreadIndex(SharedData.THREAD_3);
                    }
                    
                    sharedData.notifyAll();
                    try {
                        while(sharedData.getCurrentThreadIndex() != SharedData.THREAD_1 && !sharedData.isIsStop()) {
                            sharedData.wait();
                        }
                        
                        if(sharedData.isIsStop()) {
                            break;
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            
            sharedData.setIsStop(true);
            synchronized(sharedData) {
                sharedData.notifyAll();
            }
        } 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 {
            try {
                if(fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                if(reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                if(bReader != null) {
                    bReader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
}


#Student.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 aptech.java2.bt1104;

import java.io.Serializable;

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

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

    public String getStudRollNo() {
        return studRollNo;
    }

    public void setStudRollNo(String studRollNo) {
        this.studRollNo = studRollNo;
    }
}


#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 aptech.java2.bt1104;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @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 currentThreadIndex = 1;
    
    boolean isStop = false;
    
    public SharedData() {
        validRollNumber = new ArrayList<>();
        unvalidRollNumber = new ArrayList<>();
    }
    
    private void addValidaRollNumber(String rollNo) {
        Student std = new Student(rollNo);
        validRollNumber.add(std);
    }
    
    private void addUnvalidRollNumber(String rollNo) {
        unvalidRollNumber.add(rollNo);
    }
    
    public Student getValidStudentLast() {
        return validRollNumber.get(validRollNumber.size() - 1);
    }
    
    public String getUnvalidRollNoLast() {
        return unvalidRollNumber.get(unvalidRollNumber.size() - 1);
    }
    
    public boolean addRollNo(String rollNo) {
        String exp = "^[CTN]{1}[0-9]{4}[G-M]{1}[V]?[0-9]{4}$";
        Pattern pattern = Pattern.compile(exp);
        Matcher matcher = pattern.matcher(rollNo);
        
        if(matcher.find()) {
            addValidaRollNumber(rollNo);
            return true;
        } else {
            addUnvalidRollNumber(rollNo);
            return false;
        }
    }

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

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

    public int getCurrentThreadIndex() {
        return currentThreadIndex;
    }

    public void setCurrentThreadIndex(int currentThreadIndex) {
        this.currentThreadIndex = currentThreadIndex;
    }

    public boolean isIsStop() {
        return isStop;
    }

    public void setIsStop(boolean isStop) {
        this.isStop = isStop;
    }
}


#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 aptech.java2.bt1104;

/**
 *
 * @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();
    }
}


#student.txt


C1009H0001
T0812KV0002
TT0812KV0002
C1009H00012
C10030003
C1103T004
G1103T004



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

2021-03-18 15:18:27


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

/**
 *
 * @author MyPC
 */
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();
    }
}


#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 Java2.lesson4.TongHop;

import java.util.ArrayList;

/**
 *
 * @author MyPC
 */
public class SharedData extends Student{
    ArrayList<Student> validRollNumber = new ArrayList<>();
    ArrayList<String> unvalidRollNumber = new ArrayList<>();
    int check = 1;
    boolean end = false;
    int validSize = 0;
    int kiemtra = 0;
    
    @Override
    public String getStudRollNo() {
        return studRollNo;
    }

    @Override
    public void setStudRollNo(String studRollNo) {
        this.studRollNo = studRollNo;
    }
    
    public void addValid(Student student){
        validRollNumber.add(student);
    }
    
    public void addUnvalid(String string){
        unvalidRollNumber.add(string);
    }
    
    public int getValidSize(){
        return validRollNumber.size();
    }
}


#Student.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.TongHop;

/**
 *
 * @author MyPC
 */
public class Student {
    String studRollNo;
    

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

    public Student() {
    }

    public String getStudRollNo() {
        return studRollNo;
    }

    public void setStudRollNo(String studRollNo) {
        this.studRollNo = studRollNo;
    }
    
    
}


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

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

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


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

    
    
    
    
    @Override
    public void run() {
        try {
            sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        FileInputStream fis = null;
        InputStreamReader reader = null;
        BufferedReader bReader = null;
        try {
            fis = new FileInputStream("students.txt");
            reader = new InputStreamReader(fis);
            bReader = new BufferedReader(reader);
            String line;
            
            while((line = bReader.readLine()) != null){
                synchronized(sharedData){
                    if(line.length() < 10 || line.length() > 11){
                        sharedData.addUnvalid(line);
                        sharedData.notifyAll();
                        sharedData.check = 0;
                        sharedData.setStudRollNo(line);
                        sharedData.wait();
                        continue;
                    }
                    if(line.charAt(0) != 'C' && line.charAt(0) != 'T' && line.charAt(0) != 'N'){
                        sharedData.addUnvalid(line);
                        sharedData.notifyAll();
                        sharedData.check = 0;
                        sharedData.setStudRollNo(line);
                        sharedData.wait();
                        continue;
                    }
                    if(line.charAt(1) < 48 || line.charAt(1) > 57 || line.charAt(2) < 48 || line.charAt(2) > 57 || line.charAt(3) < 48 || line.charAt(3) > 57 || line.charAt(4) < 48 || line.charAt(4) > 57){
                        sharedData.addUnvalid(line);
                        sharedData.notifyAll();
                        sharedData.check = 0;
                        sharedData.setStudRollNo(line);
                        sharedData.wait();
                        continue;
                    }
                    if(line.charAt(5) != 'G' && line.charAt(5) != 'H' && line.charAt(5) != 'I' && line.charAt(5) != 'K' && line.charAt(5) != 'L' && line.charAt(5) != 'M'){
                        sharedData.addUnvalid(line);
                        sharedData.notifyAll();
                        sharedData.check = 0;
                        sharedData.setStudRollNo(line);
                        sharedData.wait();
                        continue;
                    }
                    if(line.charAt(6) == 'V'){
                        if(line.charAt(7) < 48 || line.charAt(7) > 57 || line.charAt(8) < 48 || line.charAt(8) > 57 || line.charAt(9) < 48 || line.charAt(9) > 57 || line.charAt(10) < 48 || line.charAt(10) > 57){
                            sharedData.addUnvalid(line);
                            sharedData.notifyAll();
                            sharedData.check = 0;
                            sharedData.setStudRollNo(line);
                            sharedData.wait();
                            continue;
                        }
                    }else{
                        if(line.charAt(6) < 48 || line.charAt(6) > 57 || line.charAt(7) < 48 || line.charAt(7) > 57 || line.charAt(8) < 48 || line.charAt(8) > 57 || line.charAt(9) < 48 || line.charAt(9) > 57){
                            sharedData.addUnvalid(line);
                            sharedData.notifyAll();
                            sharedData.check = 0;
                            sharedData.setStudRollNo(line);
                            sharedData.wait();
                            continue;
                        }
                    }
                    Student std = new Student(line);
                    sharedData.addValid(std);
                    sharedData.notifyAll();
                    sharedData.check = 1;
                    sharedData.setStudRollNo(line);
                    sharedData.wait();

                }
            }
            synchronized(sharedData){
                sharedData.notifyAll();
                sharedData.end = true;
            }
        } 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);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                fis.close();
            } catch (IOException 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.TongHop;

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

/**
 *
 * @author MyPC
 */
public class Thread2 extends Thread{
//    Student student;
    SharedData sharedData;

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

    

    @Override
    public void run() {
        while(sharedData.end == false){
            synchronized(sharedData){
                if(sharedData.check == 1){
                    if(sharedData.kiemtra == 0){
                        sharedData.kiemtra++;
                        sharedData.notifyAll();
                        try {
                            sharedData.wait();
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    if(sharedData.check == 1){
                        try {
                            sleep(1000);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        System.out.println("Welcome student has roll number is : " + sharedData.getStudRollNo());
                        System.out.println("Valid collection has length: " + sharedData.getValidSize());
                        writeFile(sharedData.getStudRollNo());
                        sharedData.notifyAll();
                        try {
                            sharedData.wait();
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }else{
                        try {
                            sharedData.wait();
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    
                }else{
//                    student.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
    public void writeFile(String rollNo){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(rollNo + ".dat");
            byte[] b = rollNo.getBytes();
            fos.write(b);
        } 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{
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}


#Thread3.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.TongHop;

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

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

    

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

    @Override
    public void run() {
        try {
            sleep(50);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
        }
        while(sharedData.end == false){
            synchronized(sharedData){
                if(sharedData.check == 0){
                    try {
                        sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    System.out.println("Unvalid roll number : " + sharedData.getStudRollNo());
                    writeFile(sharedData.getStudRollNo());
                    sharedData.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }else{
//                    student.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    private void writeFile(String studRollNo) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("unvalid.txt",true);
            byte[] b = studRollNo.getBytes();
            String a = "\n";
            byte[] c = a.getBytes();
            fos.write(b);
            fos.write(c);
        } 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{
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
}



Nguyễn Hoàng Anh [C1907L]
Nguyễn Hoàng Anh

2020-05-27 16:08: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 javaadvanced_file_oop_thread;

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

/**
 *
 * @author Redmibook 14
 */
public class SharedData {

    List<Student> validRollNumber = new ArrayList();
    List<String> invalidRollNumber = new ArrayList();

    int chooseThread;
    Boolean t2, t3;
    Boolean isDead = false;
    public List getValidRollNumber() {
        return validRollNumber;

    }

    public List getInvalidRollNumber() {
        return invalidRollNumber;
    }

    public int getChooseThread() {
        return chooseThread;
    }

    public void setChooseThread(int chooseThread) {
        this.chooseThread = chooseThread;
    }

    public void setT2StillTrue(Boolean t2) {
        this.t2 = t2;
    }

    public Boolean getT2StillTrue() {

        return t2;
    }
      public void setT3StillTrue(Boolean t3) {
        this.t3 = t3;
    }

    public Boolean getT3StillTrue() {

        return t3;
    }
     public void setDead(Boolean isDead) {

        this.isDead = isDead;
    }
      public Boolean Dead() {

        return isDead;
    }

}



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

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

/**
 *
 * @author Redmibook 14
 */
public class Student implements Serializable{

    String studRollNo;

    public Student() {
    }

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

    public String getStudRollNo() {
        return studRollNo;
    }

    public void setStudRollNo(String studRollNo) {
        this.studRollNo = studRollNo;
    }

  
}



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

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;
import java.util.regex.Pattern;

/**
 *
 * @author Redmibook 14
 */
public class Thread1 extends Thread {

    SharedData sharedData;

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

    public String[] readFile() {
        FileReader fr = null;
        BufferedReader br = null;
        StringBuilder str = new StringBuilder();
        try {
            fr = new FileReader("students.txt");
            br = new BufferedReader(fr);
            int c;

            while ((c = br.read()) != -1) {
                str.append((char) c);
            }
        } 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);
        }
        if (fr != null) {
            try {
                br.close();
                fr.close();
            } catch (IOException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        String[] arr = str.toString().split("\n");

        return arr;
    }

    public Boolean checkRollNo(String rollNo) {
        Pattern pattern = Pattern.compile("[CNT]\\d{4}[GHIKLM]V{0,1}\\d{4}");
        if (pattern.matcher(rollNo).matches()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void run() {
        try {
            sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        String[] arrRollNo = readFile();

        for (int i = 0; i < arrRollNo.length; i++) {
            synchronized (sharedData) {
                 if (sharedData.Dead()) {
                  break;
                }
                if (checkRollNo(arrRollNo[i].trim()) == true) {
                    Student std = new Student(arrRollNo[i].trim());
                    sharedData.getValidRollNumber().add(std);

                    sharedData.setChooseThread(1);

                    sharedData.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } else {
                    sharedData.getInvalidRollNumber().add(arrRollNo[i].trim());
                    sharedData.setChooseThread(2);
                    sharedData.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (sharedData.getValidRollNumber().size() + sharedData.getInvalidRollNumber().size() == arrRollNo.length ) {
                    sharedData.setDead(Boolean.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 javaadvanced_file_oop_thread;

import java.io.File;
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 Redmibook 14
 */
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(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
            sharedData.setT2StillTrue(true);
            while (sharedData.getT2StillTrue() ) {
                if (sharedData.getChooseThread() == 1) {
                    int length = sharedData.getValidRollNumber().size() - 1;
                    String rolNo = sharedData.validRollNumber.get(length).studRollNo;
                    System.out.println("Welcome student has roll number is : " + rolNo);
                    System.out.println("Valid collection has length : " + (length + 1));
                    File file = new File(rolNo);
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;
                    try {
                        fos = new FileOutputStream(file);
                        oos = new ObjectOutputStream(fos);
                        oos.writeObject(sharedData.validRollNumber.get(length));
                        fos.close();
                        oos.close();
                    } 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);
                    }
                    
                }
              
                sharedData.notifyAll();
                try {
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
                  if(sharedData.Dead()){
                    break;
                }
            }
           
        }
    }
}



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

import java.io.File;
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 Redmibook 14
 */
public class Thread3 extends Thread {

    SharedData sharedData;

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

    @Override
    public void run() {
        synchronized (sharedData) {

            sharedData.setT3StillTrue(true);

            while (sharedData.getT3StillTrue() && !sharedData.Dead()) {
                try {
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (sharedData.getChooseThread() == 2) {

                    int length = sharedData.getInvalidRollNumber().size() - 1;
                    String rolNo = sharedData.getInvalidRollNumber().get(length).toString();
                    System.out.println("Unvalid roll number : " + rolNo);
                    System.out.println("Valid collection has length : " + (length + 1));
                    try {
                        sharedData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (sharedData.Dead()) {
                    break;
                }
            }
        }
    }
}



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

/**
 *
 * @author Redmibook 14
 */
public class main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Student std = new Student();
        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();
    }

}



trung [C1907L]
trung

2020-05-26 17:13:52



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

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

/**
 *
 * @author prdox
 */
public class Student implements Serializable{

    String studRollNo;

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

    public String getStudRollNo() {
        return studRollNo;
    }

    public void setStudRollNo(String studRollNo) {
        this.studRollNo = studRollNo;
    }

    public static boolean checkRollNo(String rollNo) {
        Pattern r = Pattern.compile("^[CTN]\\d{4}[GHIKLKM]V{0,1}\\d{4}$");
        return r.matcher(rollNo).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 homework;

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 prdox
 */
public class Thread1 extends Thread {

    @Override
    public void run() {
        synchronized (sharedData.getInstance()) {
            if (!sharedData.getInstance().isT1()) {
                try {
                    sharedData.getInstance().wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            FileReader fr = null;
            BufferedReader br = null;
            String readLn;
            try {
                fr = new FileReader("students.txt");
                br = new BufferedReader(fr);
                while ((readLn = br.readLine()) != null) {
                    if (Student.checkRollNo(readLn)) {
                        Student newStudent = new Student(readLn);
                        sharedData.getInstance().getValidRollNumber().add(newStudent);
                        sharedData.getInstance().setT2(true);
                    } else {
                        sharedData.getInstance().getInvalidRollNumber().add(readLn);
                        sharedData.getInstance().setT3(true);
                    }
                    sharedData.getInstance().setT1(false);
                    sharedData.getInstance().notifyAll();
                    sharedData.getInstance().wait();
                }
                sharedData.getInstance().setStop(true);
                sharedData.getInstance().notifyAll();
                
            } 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);
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (fr != null) {
                    try {
                        fr.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException 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 homework;

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 prdox
 */
public class Thread2 extends Thread {

    @Override
    public void run() {

        synchronized (sharedData.getInstance()) {
            while (true) {
                while (!sharedData.getInstance().isT2()) {
                    if (sharedData.getInstance().isStop()) {
                        return;
                    }
                    try {
                        sharedData.getInstance().wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                Student newStudent = sharedData.getInstance().getValidRollNumber().get(sharedData.getInstance().getValidRollNumber().size() - 1);
                System.out.println("Welcome student has roll number is"
                        + newStudent.getStudRollNo());
                System.out.println("Valid collection has length : " + sharedData.getInstance().getValidRollNumber().size());
                //write to file xxx.dat
                FileOutputStream fos = null;
                ObjectOutputStream oos = null;
                String fileName = newStudent.getStudRollNo() + ".dat";
                try {
                    fos = new FileOutputStream(fileName);
                    oos = new ObjectOutputStream(fos);
                    oos.writeObject(newStudent);
                } 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 (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    if (oos != null) {
                        try {
                            oos.close();
                        } catch (IOException ex) {
                            Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
                sharedData.getInstance().notifyAll();
                sharedData.getInstance().setT1(true);
                sharedData.getInstance().setT2(false);
            }
        }
//        synchronized (sharedData.getInstance()) {
//            sharedData.getInstance().setT3(true);
//            sharedData.getInstance().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 homework;

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

/**
 *
 * @author prdox
 */
public class Thread3 extends Thread {

    @Override
    public void run() {

        synchronized (sharedData.getInstance()) {
            while (true) {
                while (!sharedData.getInstance().isT3()) {
                    if (sharedData.getInstance().isStop()) {
                        return;
                    }
                    try {
                        sharedData.getInstance().wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.out.println("Invalid roll number: "
                        + sharedData.getInstance().getInvalidRollNumber().get(sharedData.getInstance().getInvalidRollNumber().size() - 1));
                FileOutputStream fos = null;

                try {
                    fos = new FileOutputStream("invalid.txt", true);
                    byte[] b = sharedData.getInstance().getInvalidRollNumber().
                            get(sharedData.getInstance().getInvalidRollNumber().size() - 1).getBytes();
                    fos.write(b);
                } 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);
                        }
                    }
                }

                sharedData.getInstance().setT1(true);
                sharedData.getInstance().setT3(false);
                sharedData.getInstance().notifyAll();
            }
        }
//        synchronized (sharedData.getInstance()) {
//            sharedData.getInstance().setT2(true);
//            sharedData.getInstance().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 homework;

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

/**
 *
 * @author prdox
 */
public class sharedData {

    List<Student> validRollNumber = null;
    List<String> invalidRollNumber = null;
    boolean t1,t2,t3,stop;

    private static sharedData instance;

    public sharedData() {
        validRollNumber = new ArrayList<>();
        invalidRollNumber = new ArrayList<>();
    }

    public static synchronized sharedData getInstance() {
        if (instance == null) {
            instance = new sharedData();
        }
        return instance;
    }

    public boolean isStop() {
        return stop;
    }

    public void setStop(boolean stop) {
        this.stop = stop;
    }

    public void setT1(boolean t1) {
        this.t1 = t1;
    }

    public void setT2(boolean t2) {
        this.t2 = t2;
    }

    public void setT3(boolean t3) {
        this.t3 = t3;
    }

    public boolean isT1() {
        return t1;
    }

    public boolean isT2() {
        return t2;
    }

    public boolean isT3() {
        return t3;
    }

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

    public List<String> getInvalidRollNumber() {
        return invalidRollNumber;
    }
    
}



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

/**
 *
 * @author prdox
 */
public class Main {

    public static void main(String[] args) {
        Thread1 t1 = new Thread1();
        Thread2 t2 = new Thread2();
        Thread3 t3 = new Thread3();
        sharedData.getInstance().setStop(false);
        sharedData.getInstance().setT1(true);
        sharedData.getInstance().setT2(false);
        sharedData.getInstance().setT3(false);
        t1.start();
        t2.start();
        t3.start();
    }

}



NguyenHuuThanh [T1907A]
NguyenHuuThanh

2020-04-01 18:03: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 filethread;

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

    /**
     * @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 filethread;

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

/**
 *
 * @author abc
 */
public class Student implements Serializable {
    String rollNo;  // thuoc tinh cua student
    
    public Student() // ham tao khong doi
    {
        
    }
    
    

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

    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
    
    
    public static boolean checkValidateRollNo(String rollNo) // dung static thi k can khoi tao ra
    {
        String pattern = "[CTN][0-9]{4}[G-M][V]?[0-9]{4}";
        // ky tu dau = C or T or N 
        // ky tu 2 gom 4 ky tu tu 0 den 9
        
        boolean matches = Pattern.matches(pattern, rollNo);
        
        
        return matches; // tim thay = true
        
        //else = false
        
    }
}
/*
 * 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 filethread;

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

/**
 *
 * @author abc
 */
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> invalidRollNumber;
    int currentThread;
    
    boolean alive;  // check 

    public boolean isAlive() {
        return alive;
    }

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

   
    
    public SharedData()
    {
        validRollNumber = new ArrayList<>();
        invalidRollNumber = new ArrayList<>();
        alive = true;
    }

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

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

    public List<String> getInvalidRollNumber() {
        return invalidRollNumber;
    }

    public void setInvalidRollNumber(List<String> invalidRollNumber) {
        this.invalidRollNumber = invalidRollNumber;
    }

    public int getCurrentThread() {
        return currentThread;
    }

    public void setCurrentThread(int currentThread) {
        this.currentThread = currentThread;
    }
     
    
    
    
}
/*
 * 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 filethread;

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 abc
 */
public class Thread1 extends Thread {
    //doc du lieu tu student.txt
    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);
        }
       // khai bao FileReader va BufferdReader
         FileReader reader = null;
         BufferedReader bufferedReader = null;
          try {
            // doc du lieu tu student.txt

       // Code duy nhat surround by try - catch 
         reader = new FileReader("student.txt");
         bufferedReader = new BufferedReader(reader);
         
         String line = null;
         
         // kiem tra da doc het line chua . Neu = null thi dung while
         while(sharedData.isAlive())
         {
             // qua trinh doc du lieu file
             // sync du lieu tu day :
             synchronized(sharedData)
             {
                 line = bufferedReader.readLine();
                 if (line == null)
                 {
                     sharedData.setAlive(false);
                     break;
                     
                 }
                 
                 
                 // check neu rollNo hop le
                 boolean isValid = Student.checkValidateRollNo(line); 
                 // neu rollno hop le
                 if(isValid)
                 {
                     // tao 1 hoc sinh moi = constructor co tham so
                     // public Student(String rollNo) {
                     //     this.rollNo = rollNo;
                     //       }
                     Student std = new Student(line);
                      
                     // add Student vao sharedData
                     sharedData.getValidRollNumber().add(std); 
                     sharedData.setCurrentThread(sharedData.THREAD_2); // chuyển sang luồng 2
                     
                     
                 }
                 
                 else
                 {
                     // neu sai thi lay "line" = invalid
                     sharedData.getInvalidRollNumber().add(line);
                     // chuyen sang thread 3
                     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
        {
            // check if reader != null
            if(reader != null)
            {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //check if bufferedReader != null
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
          // ket thuc doc du lieu tu student.txt
   }
}
/*
 * 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 filethread;

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 abc
 */
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.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" + std.getRollNo());
                    System.out.println("Length : " + length);
                  
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;
                    try {
                        // ghi vao file .txt

                        fos = new FileOutputStream(std.getRollNo() + ".dot");
                        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);
                
            }
            
            
        }
    }
    
}
/*
 * 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 filethread;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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(){
        FileOutputStream fos = null;
        try {
             fos = new FileOutputStream("invalidate.txt");
             
             while(sharedData.isAlive())
             {
                 synchronized(sharedData)
                 {
                     sharedData.notifyAll();
                     try {
                         while(sharedData.getCurrentThread() != SharedData.THREAD_3)
                         {
                             sharedData.wait();
                         }
                     } catch (InterruptedException ex) {
                         Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
                     }
                     int length = sharedData.getInvalidRollNumber().size();
                     
                     String rollNo = sharedData.getInvalidRollNumber().get( length -1);
                     
                     System.out.println("Invalid roll number :" + rollNo);
                     
                     
                     rollNo += "\n";
                    byte[] b = rollNo.getBytes();
                    fos.write(b);
                     
                     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);
                }
            }
        }
        
        
    }
    
}



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

2020-04-01 15:30:15



package java2_Advanced.BaiTapNgay30_3_2020.OnLuyenTongHop_File_OOP_Thread;

import java.util.regex.Pattern;

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 checkRollNo(String rollNo) {                     // check xem rollNo theo kiểu Pattern
        String pattern = "[CTN][0-9]{4}[GHIKLM][V]?[0-9]{4}";
        boolean bol = Pattern.matches(pattern,rollNo);
        return bol;
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.OnLuyenTongHop_File_OOP_Thread;

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

public class SharedData {
    int index;            // biến index để xem chạy xonh luông 1 thì luồng nào sẽ được chạy tiếp
    boolean alive;           // alive để kiểm tra nếu file student.txt rỗng thì vòng lặp while ở luồng 1,2,3 sẽ dừng.
    List<Student> validRollNumber = new ArrayList<>();
    List<String> unvalidRollNumber = new ArrayList<>();

    public SharedData() {
        index = 1;
        alive = true;
    }

    public int getIndex() {
        return index;
    }

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

    public boolean isAlive() {
        return alive;
    }

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

    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;
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.OnLuyenTongHop_File_OOP_Thread;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Thread1 extends Thread{
    SharedData sharedData;

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

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String line = null;
        FileReader fr = null;
        BufferedReader bf = null;
        try {
            fr = new FileReader("d:/Admin/Java2_advanced/student.txt");
            bf = new BufferedReader(fr);
            while (sharedData.isAlive()){
                synchronized (sharedData){
                    line = bf.readLine();             // đọc dữ liệu từ file

                    if (line == null) {              // nếu file rỗng  thì sẽ dừng vòng lặp k đọc nữa.
                        sharedData.setAlive(false);
                        break;
                    }

                    boolean check = Student.checkRollNo(line);      // kiểm tra xem rollNo có đúng k
                    if (check) {                                      // nếu đúng sẽ lưu vào validRollNoNumber và chạy luồng 2
                        Student student = new Student(line);
                        sharedData.getValidRollNumber().add(student);
                        sharedData.setIndex(2);
                    } else {                                       // nếu ko đúng sẽ lưu vào unvalidRollNoNumber và chạy luồng 3

                        sharedData.getUnvalidRollNumber().add(line);
                        sharedData.setIndex(3);
                    }
                    sharedData.notifyAll();
                    try {
                        sharedData.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                synchronized (sharedData){
                    sharedData.notifyAll();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //đóng file
            if (bf != null) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.OnLuyenTongHop_File_OOP_Thread;


import java.io.*;

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.getIndex() != 2 && sharedData.isAlive()) {
                        sharedData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int leng = sharedData.validRollNumber.size();     // khai báo độ dài của chuỗi validRollNoNumber
                if (leng > 0) {
                    Student std = sharedData.getValidRollNumber().get(leng - 1);     // gọi ra thông tin rollNo và chuyền vào Student
                    System.out.println("Welcome student has roll number is : " + std.getRollNo());
                    System.out.println("Valid collection has length : " + leng);

                    // lưu file dạng object
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;

                    try {
                        fos = new FileOutputStream("d:/Admin/Java2_advanced/" + std.getRollNo() + ".dat");
                        oos = new ObjectOutputStream(fos);

                        oos.writeObject(std);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (oos != null) {
                            try {
                                oos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                } else {
                    System.err.println(" khong co rollNo nao hoac lay thong tin tu file loi");
                }
                sharedData.setIndex(1);

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



package java2_Advanced.BaiTapNgay30_3_2020.OnLuyenTongHop_File_OOP_Thread;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Thread3 extends Thread {
    SharedData sharedData;

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

    @Override
    public void run() {
        while (sharedData.isAlive()) {
            synchronized (sharedData) {
                sharedData.notifyAll();
                try {
                    while (sharedData.getIndex() != 3 && sharedData.isAlive()) {
                        sharedData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                int leng = sharedData.getUnvalidRollNumber().size();
                String roll = sharedData.getUnvalidRollNumber().get(leng - 1);
                System.out.println("Unvalid roll number: " + roll);

                // ghi file
                FileOutputStream fos = null;
                BufferedOutputStream bfos = null;
                try {
                    fos = new FileOutputStream("d:/Admin/Java2_advanced/unvalid.txt");
                    bfos = new BufferedOutputStream(fos);
                    roll = roll + "\n";
                    byte[] bytes = roll.getBytes();
                    bfos.write(bytes);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bfos != null) {
                        try {
                            bfos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                sharedData.setIndex(1);
            }
            synchronized (sharedData) {
                sharedData.notifyAll();
            }
        }
    }
}



package java2_Advanced.BaiTapNgay30_3_2020.OnLuyenTongHop_File_OOP_Thread;

public class Test {
    public static void main(String[] args) {
        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();
    }
}