Bài toán đa luồng (MultiThreading in java) đọc File trong Java
1. Viết 1 chương trình Java thực hiện công việc sau:
Ghi dữ liệu xuống file ”number.txt” với:
- Dòng đầu tiên ghi 1 số ngẫu nhiên n (với 10 <= n <=100)
- Mỗi dòng tiếp theo ghi 1 số nguyên dương ngẫu nhiên từ 1 đến 500
2. Viết chương trình Java khác để thực hiện công việc:
Sử dụng 3 threads:
- Thread thứ nhất sau mỗi giây sẽ đọc dữ liệu là một số trong file “number.txt” sau giá trị n đầu tiên
Nếu số đọc được là chẵn thì chuyển qua thread 2
Nếu số đọc được là lẻ thì chuyển qua thread 3
- Thread 2:
Ngay sau khi nhận được số vừa đọc từ thread 1 thì nó sẽ in ra tất cả các ước số của số này
Ví dụ: Thread -2: 18 = 1, 2, 3, 6, 9, 18
- Thread 3:
Ngay sau khi nhận được số vừa đọc từ thread 1 thì nó sẽ hiển thị lên là bình phương của số đó
Đồng bộ 3 thread này (dùng synchronized)
Ví dụ file data sau khi được ghi:
10 83465378128945576 |
(Không được ghi số nguyên âm vào file này, kể cả số 0)
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)
Hieu Ngo
2021-09-14 08:43:39
#Main.java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String [] args) {
List<Integer> list = new ArrayList<>();
addRandom(list);
saveFile(list);
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
ThreadThree t3 = new ThreadThree();
t1.start();
t2.start();
t3.start();
}
private static void addRandom(List<Integer> list) {
Random random = new Random();
int n = random.nextInt(91) + 10;
list.add(n);
for(int i =0 ; i<10;i++) {
int x = random.nextInt(501) + 1;
list.add(x);
}
}
private static void saveFile(List<Integer> list) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("number.txt");
bos = new BufferedOutputStream(fos);
for(Integer number : list) {
String line = number + "\n";
byte[] b = line.getBytes(StandardCharsets.UTF_8);
bos.write(b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bos!=null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Save File!");
}
}
#ShareData.java
import java.util.ArrayList;
import java.util.List;
public class ShareData {
int n;
int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public static final int THREAD_1 = 1;
public static final int THREAD_2 = 2;
public static final int THREAD_3 = 3;
int currentThread = THREAD_1;
public int getCurrentThread() {
return currentThread;
}
public void setCurrentThread(int currentThread) {
this.currentThread = currentThread;
}
private static ShareData instance = null;
public synchronized static ShareData getInstance() {
if(instance == null ) {
instance = new ShareData();
}
return instance;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public synchronized int index (int value) {
return value;
}
public synchronized boolean isAlive() {
return count >= 0;
}
}
#ThreadOne.java
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadOne extends Thread {
ShareData shareData;
public ThreadOne() {
this.shareData = ShareData.getInstance();
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
}
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader("number.txt");
bufferedReader = new BufferedReader(reader);
synchronized (shareData) {
String line = null;
while ((line = bufferedReader.readLine())!= null) {
line = line.trim();
int n = Integer.parseInt(line);
shareData.setN(n);
if(n%2==0) {
shareData.setCurrentThread(ShareData.THREAD_2);
} else {
shareData.setCurrentThread(ShareData.THREAD_3);
}
shareData.notifyAll();
while (shareData.getCurrentThread() != ShareData.THREAD_1 && shareData.isAlive()) {
shareData.wait();
Thread.sleep(1000);
}
}
}
System.out.println("T1 stop");
synchronized (shareData) {
shareData.notifyAll();
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
#ThreadThree.java
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadThree extends Thread {
ShareData shareData;
public ThreadThree() {
this.shareData = ShareData.getInstance();
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
}
for(int i= shareData.index(11); i> 0;i--) {
synchronized (shareData) {
shareData.notifyAll();
try {
while (shareData.getCurrentThread()!= ShareData.THREAD_3 && shareData.isAlive()) {
shareData.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int n = shareData.getN();
if(n%2 !=0) {
System.out.println("T3 >> BP " + n + " = " + n * n);
System.out.println("T3 stop");
}
shareData.setCurrentThread(ShareData.THREAD_1);
}
}
}
}
#ThreadTwo.java
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadTwo extends Thread{
ShareData shareData;
public ThreadTwo() {
this.shareData = ShareData.getInstance();
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadOne.class.getName()).log(Level.SEVERE, null, ex);
}
for(int i = shareData.index(11); i>0 ; i--) {
synchronized (shareData) {
shareData.notifyAll();
try {
while (shareData.getCurrentThread()!= ShareData.THREAD_2 && shareData.isAlive()) {
shareData.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int n = shareData.getN();
if(n%2==0) {
System.out.print("T2 >> "+ n +"= ");
for(int j =1; j<=n;j++) {
if(n%j==0) {
System.out.print(j + " ");
}
}
System.out.println();
System.out.println("T2 stop");
}
shareData.setCurrentThread(ShareData.THREAD_1);
}
}
}
}
Nguyễn Tiến Đạt
2021-03-19 09:32:43
#Java1.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.LuyenThread.BaiToanDaLuong;
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 MyPC
*/
public class Java1 {
public static void main(String[] args) {
Random random = new Random();
int n;
while(true){
if((n = random.nextInt(101)) >= 10) break;
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream("number.txt");
String a = "\n";
byte[] b = Integer.toString(n).getBytes();
fos.write(b);
b = a.getBytes();
fos.write(b);
for (int i = 0; i < n; i++) {
int m = random.nextInt(501);
b = Integer.toString(m).getBytes();
fos.write(b);
b = a.getBytes();
fos.write(b);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Java1.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Java1.class.getName()).log(Level.SEVERE, null, ex);
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Java1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
#Java2.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.LuyenThread.BaiToanDaLuong;
/**
*
* @author MyPC
*/
public class Java2 {
public static void main(String[] args) {
SharedData data = new SharedData();
Thread1 t1 = new Thread1(data);
Thread2 t2 = new Thread2(data);
Thread3 t3 = new Thread3(data);
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.LuyenThread.BaiToanDaLuong;
/**
*
* @author MyPC
*/
public class SharedData {
int num;
int threadStatus = 1;
boolean stop = false;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
#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.LuyenThread.BaiToanDaLuong;
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 MyPC
*/
public class Thread1 extends Thread{
SharedData data;
public Thread1(SharedData data) {
this.data = data;
}
@Override
public void run() {
FileInputStream fis = null;
InputStreamReader reader = null;
BufferedReader bReader = null;
try {
fis = new FileInputStream("number.txt");
reader = new InputStreamReader(fis);
bReader = new BufferedReader(reader);
String line;
int check = 0;
while((line = bReader.readLine()) != null){
if(check == 0){
check++;
continue;
}
synchronized(data){
try {
sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
int n = Integer.parseInt(line);
if( n % 2 == 0) data.threadStatus = 2;
else data.threadStatus = 3;
System.out.println("Thread 1: " + n);
data.setNum(n);
data.notifyAll();
try {
data.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
data.stop = true;
synchronized(data){
data.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);
}
}
}
#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.LuyenThread.BaiToanDaLuong;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author MyPC
*/
public class Thread2 extends Thread{
SharedData data;
public Thread2(SharedData data) {
this.data = data;
}
@Override
public void run() {
while(data.stop == false){
synchronized(data){
data.notifyAll();
while(data.threadStatus != 2 && data.stop == false){
try {
data.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(data.stop == true) break;
int n = data.getNum();
System.out.print("Thread 2: " + n + " = ");
for (int i = 1; i <= n; i++) {
if(i == 1){
System.out.print("1");
continue;
}
if(n % i == 0) System.out.print(", " + i);
}
System.out.println("");
data.threadStatus = 1;
}
}
synchronized(data){
data.notifyAll();
}
}
}
#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.LuyenThread.BaiToanDaLuong;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author MyPC
*/
public class Thread3 extends Thread{
SharedData data;
public Thread3(SharedData data) {
this.data = data;
}
@Override
public void run() {
while(data.stop == false){
synchronized(data){
data.notifyAll();
while(data.threadStatus != 3 && data.stop == false){
try {
data.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(data.stop == true) break;
int n = data.getNum();
System.out.println("Thread 3: " + n*n);
data.threadStatus = 1;
}
}
synchronized(data){
data.notifyAll();
}
}
}
thienphu
2020-04-02 13:18:03
/*
* 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 DaLuongDocFile;
/**
*
* @author Thien Phu
*/
public class Data {
int index,number;
boolean checkstatus;
public Data() {
index = 1;
checkstatus = true;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public void setCheckstatus(boolean checkstatus) {
this.checkstatus = checkstatus;
}
public boolean isCheckstatus() {
return checkstatus;
}
}
/*
* 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 DaLuongDocFile;
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 Thien Phu
*/
public class Thread1 extends Thread {
Data data;
public Thread1(Data data) {
this.data = data;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader("D:\\baitapjava\\BTThread\\src\\DaLuongDocFile\\number.txt");
bufferedReader = new BufferedReader(reader);
synchronized (data) {
String line = null;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim();
int number = Integer.parseInt(line);
data.setNumber(number);
System.out.println("T1: " + line);
if (number % 2 == 0) {
data.setIndex(2);
// System.out.println("Index = 2 hien tai");
}
if (number % 2 != 0) {
data.setIndex(3);
}
data.notifyAll();
// System.out.println("T1 Vao hang doi");
data.wait();
Thread.sleep(1000);
// System.out.println("Sau khi nghi 1s");
}
data.setCheckstatus(false);
}
} 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 {
if (reader != null) {
reader.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("T1 Stop");
synchronized(data){
data.notifyAll();
stop();
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DaLuongDocFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thien Phu
*/
public class Thread2 extends Thread {
Data data;
public Thread2(Data data) {
this.data = data;
}
@Override
public void run() {
for (int i = 0; i < 11; i++) {
synchronized (data) {
data.notifyAll();
//System.out.println("Kiem tra index hien tai: " + data.getIndex());
while (data.getIndex() != 2 && data.isCheckstatus()) {
try {
// System.out.println("Chay vao wait: index =" + data.getIndex());
data.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (data.isCheckstatus() == false) {
break;
}
System.out.println("Uoc cua :" + data.getNumber());
for (int j = 1; j < data.getNumber(); j++) {
if (data.getNumber() % j == 0) {
System.out.print(j + ",");
}
}
System.out.println("");
data.setIndex(1);
// System.out.println("index hien tai :" + data.getIndex());
// System.out.println("Chay qua day t2");
}
}
System.out.println("T2: Stop");
synchronized (data) {
stop();
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DaLuongDocFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thien Phu
*/
public class Thread3 extends Thread {
Data data;
public Thread3(Data data) {
this.data = data;
}
@Override
public void run() {
for (int i = 0; i < 11; i++) {
synchronized (data) {
data.notifyAll();
while (data.getIndex() != 3 && data.isCheckstatus()) {
try {
data.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(data.isCheckstatus()== false){
break;
}
int number = data.getNumber();
System.out.println("T3: " + number * number);
data.setIndex(1);
}
}
System.out.println("T3: Stop");
synchronized (data) {
stop();
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DaLuongDocFile;
/**
*
* @author Thien Phu
*/
public class Main2 {
public static void main(String[] args) {
Data data = new Data();
Thread1 t1 = new Thread1(data);
Thread2 t2 = new Thread2(data);
Thread3 t3 = new Thread3(data);
t2.start();
t3.start();
t1.start();
}
}
thienphu
2020-04-02 13:16:54
/*
* 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 DaLuongDocFile;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Thien Phu
*/
public class ShareData {
int index;
List<Integer> danhsach;
public ShareData() {
this.danhsach = new ArrayList<>();
index = 1;
}
public void setDanhsach(List<Integer> danhsach) {
this.danhsach = danhsach;
}
public List<Integer> getDanhsach() {
return danhsach;
}
public void setIndex(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
}
/*
* 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 DaLuongDocFile;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thien Phu
*/
public class SaveFile extends Thread {
ShareData shareData;
public SaveFile(ShareData shareData) {
this.shareData = shareData;
}
@Override
public void run() {
Random random = new Random();
int number = random.nextInt(91) + 10;
shareData.danhsach.add(number);
for (int i = 0; i < 10; i++) {
int r = random.nextInt(501) + 1;
shareData.danhsach.add(r);
}
//System.out.println("Bat dau ghi file:");
//ghi xuong file
FileOutputStream fos = null;
BufferedOutputStream bos = null;
// System.out.println("Chay qua day");
try {
fos = new FileOutputStream("D:\\baitapjava\\BTThread\\src\\DaLuongDocFile\\number.txt");
bos = new BufferedOutputStream(fos);
for (Integer so : shareData.danhsach) {
String line = so + "\n";
/// System.out.println("Gtri Line: " + line);
byte[] b = line.getBytes("utf8");
bos.write(b);
//System.out.println("Co chay vao day: " + b);
}
} 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 {
try {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
}
}
}
}
/*
* 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 DaLuongDocFile;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thien Phu
*/
public class Main {
public static void main(String[] args) {
ShareData shareData = new ShareData();
SaveFile savefile = new SaveFile(shareData);
savefile.start();
}
}
Trương Công Vinh
2020-03-30 11:12:43
/*
* 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 testThreadandFile;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DELL
*/
public class Thread1 extends Thread{
shareData shareData;
int count =0;
public Thread1(shareData shareData) {
this.shareData = shareData;
}
@Override
public void run() {
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader("d:/Java2/number.txt");
bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null ) {
synchronized(shareData){
count++;
shareData.setCount(count);
int n = Integer.parseInt(line);
shareData.setN(n);
System.out.println("\n\nT1 >> index : "+shareData.getCount()+">>"+shareData.getN());
if (n%2==0) {
shareData.setIndex(2);
System.out.println("Chia het cho 2 .");
}else{
shareData.setIndex(3);
System.out.println("khong chia het cho 2 .");
}
shareData.notifyAll();
shareData.wait();
}
}
} catch (Exception e) {
System.err.println("Loi doc file !");
}
}
}
/*
* 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 testThreadandFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DELL
*/
public class Thread2 extends Thread {
shareData shraData;
public Thread2(shareData shraData) {
this.shraData = shraData;
}
@Override
public void run() {
for (int i = 0;i<25; i++) {
synchronized(shraData){
shraData.notifyAll();
try {
while (shraData.getIndex()!= 2 && shraData.getCount()<25) {
shraData.wait();
}
} catch (InterruptedException ex) {
Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
}
int n = shraData.getN();
if (n % 2 == 0) {
System.out.print("\n\nT2 >>> ");
for (int j = 1; j < n; j++) {
if ( n % j == 0) {
System.out.print(j + " , ");
}
}
}
shraData.setIndex(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 testThreadandFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DELL
*/
public class Thread3 extends Thread {
shareData share;
public Thread3(shareData share) {
this.share = share;
}
@Override
public void run() {
for (int i = 0;i<25 ; i++) {
synchronized (share) {
share.notifyAll();
try {
while (share.getIndex()!=3 && share.getCount()<25) {
share.wait();
}
} catch (InterruptedException ex) {
Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex);
}
int n = share.getN();
if (n % 2 != 0) {
n *= n;
System.out.println(" \n\nT3 >> " + n);
}
share.setIndex(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 testThreadandFile;
import java.io.Serializable;
/**
*
* @author DELL
*/
public class RadNumber implements Serializable{
int songuyen ;
public RadNumber() {
}
public int getSonguyen() {
return songuyen;
}
public void setSonguyen(int songuyen) {
this.songuyen = songuyen;
}
public String getLine(){
return songuyen + "\n";
}
public void parseLine(String line) {
//remove whiteplace
line = line.trim();
String[] params = line.split(" ");
if(params.length < 1) {
System.out.println("Data error");
return;
}
songuyen = Integer.parseInt(params[0]);
}
}
/*
* 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 testThreadandFile;
/**
*
* @author DELL
*/
public class shareData {
int n;
int index = 1;
int count ;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public shareData() {
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
}
/*
* 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 testThreadandFile;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DELL
*/
public class Main {
static Random random = new Random();
public static void main(String[] args) {
shareData shaData = new shareData();
ArrayList<RadNumber> list = new ArrayList<>();
addRandom(list);
saveFile(list);
Thread1 t1 = new Thread1(shaData);
Thread2 t2 = new Thread2(shaData);
Thread3 t3 = new Thread3(shaData);
t1.start();
t2.start();
t3.start();
}
private static void addRandom(ArrayList<RadNumber> list) {
RadNumber data = new RadNumber();
data.setSonguyen(random.nextInt(90) + 10);
list.add(data);
for (int i = 1; i < 25; i++) {
data = new RadNumber();
int n1 = random.nextInt(500) + 1;
data.setSonguyen(n1);
list.add(data);
}
}
private static void saveFile(ArrayList<RadNumber> list) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("d:/Java2/number.txt");
bos =new BufferedOutputStream(fos);
for (RadNumber data : list) {
String line = data.getLine();
byte[] b;
b = line.getBytes("utf8");
bos.write(b);
}
} catch (IOException ex){
System.err.println("Loi ghi file !!!");
}finally{
if (bos!= null) {
try {
bos.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
System.out.println("Save file !");
}
}