Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ua.nure.kudria.practice5;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * @author Artem Kudria
- */
- public final class Part5 {
- private static final String FILE_NAME = "part5.txt";
- private static final List<Thread> threadList = new ArrayList<>();
- private Part5() {
- }
- public static void main(String[] args) {
- try {
- final RandomAccessFile accessFile = new RandomAccessFile(FILE_NAME, "rw");
- for (int i = 0; i < 10; i++) {
- synchronized (accessFile) {
- Thread thread = new Thread(new RandomThread(accessFile, i));
- threadList.add(thread);
- thread.start();
- }
- }
- synchronized (threadList) {
- // accessFile.close();
- }
- } catch (IOException e) {
- System.err.println(e.getMessage());
- }
- new Thread(() -> {
- synchronized (threadList) {
- try {
- System.out.println(read());
- } catch (IOException e) {
- System.err.println(e.getMessage());
- }
- }
- }).start();
- }
- public static String read() throws IOException {
- RandomAccessFile file;
- file = new RandomAccessFile(FILE_NAME, "r");
- String res = "";
- int b = file.read();
- while (b != -1) {
- res = res + (char) b;
- b = file.read();
- }
- file.close();
- return res;
- }
- }
- class RandomThread implements Runnable {
- private int number;
- private final RandomAccessFile randomAccessFile;
- public RandomThread(RandomAccessFile randomAccessFile, int number) {
- this.number = number;
- this.randomAccessFile = randomAccessFile;
- }
- @Override
- public void run() {
- synchronized (randomAccessFile) {
- try {
- randomAccessFile.seek(randomAccessFile.length());
- for (int i = 0; i < 20; i++) {
- randomAccessFile.writeBytes(Integer.toString(number));
- Thread.sleep(1);
- }
- randomAccessFile.write(System.lineSeparator().getBytes());
- } catch (IOException | InterruptedException e) {
- System.err.println(e.getMessage());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement