StefanTodorovski

(Java) OS: Lab 2 - ОС: Лаб 2

Apr 4th, 2019
4,693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.17 KB | None | 0 0
  1. /*
  2. Task 1 Problem 1 (1 / 1)
  3. Execute the TwoThreads.java example. Then modify the program so that it uses only one thread class, ThreadAB. In the constructor of the class you should pass the two strings which should be printed by the corresponding instance. The thread should not inherit from the Thread class. The new program should behave the same way as the original one, i.e. you must have two threads again which will separately execute the run() method: one thread will print A and B, while the other one will print 1 and 2.
  4.  
  5. What would happen if one thread needs to print out the entire alphabet, and the other the numbers from 1 to 26? Can you predict the program output correctly?
  6. */
  7.  
  8. public class TwoThreads {
  9. //    public static class Thread1 extends Thread {
  10. //        public void run() {
  11. //            System.out.println("A");
  12. //            System.out.println("B");
  13. //        }
  14. //    }
  15. //
  16. //    public static class Thread2 extends Thread {
  17. //        public void run() {
  18. //            System.out.println("1");
  19. //            System.out.println("2");
  20. //        }
  21. //    }
  22.  
  23.     public static class ThreadAB implements Runnable {
  24.         String[] str;
  25.  
  26.         ThreadAB(String... str) {
  27.             this.str = str;
  28.         }
  29.  
  30.         @Override
  31.         public void run() {
  32.             for(String string : str) {
  33.                 System.out.println(string);
  34.             }
  35.         }
  36.     }
  37.  
  38.     public static void main(String[] args) {
  39. //        new Thread1().start();
  40. //        new Thread2().start();
  41.  
  42.         //Thread() konstruktorot prima Runnable objekti
  43.         Thread threadAlphabet = new Thread(new ThreadAB("A", "B", "C", "D", "E", "F", "G", "H"));
  44.         Thread threadNumbers = new Thread(new ThreadAB("1", "2", "3", "4", "5", "6", "7"));
  45.         threadAlphabet.start();
  46.         threadNumbers.start();
  47.         //Outputot nemoze da se predvidi, se izvrsuvaat "paralelno"
  48.     }
  49. }
  50.  
  51.  
  52.  
  53. /*
  54. Task 2 Problem 1 (1 / 1)
  55. Solve the issue of detecting the number of occurrences of the number 3 in a large array by using thread synchronization methods. The counts are written / incremented in the global variable count on each find.
  56.  
  57. The standard sequential solution is not acceptable as it takes a long time (because the array is very large). Therefore, you need to implement this process and write a method which will count the occurrences of 3 in smaller fragments of the array, while the result is still kept in the global count variable.
  58.  
  59. Note: The starting code for the solutions is given in CountThree.java. You need to test it with an array of at least 1.000 elements.
  60. */
  61.  
  62. import java.util.HashSet;
  63. import java.util.Random;
  64. import java.util.Scanner;
  65. import java.util.concurrent.Semaphore;
  66.  
  67. public class CountThree {
  68.  
  69.     public static int NUM_RUNS = 100;
  70.     /**
  71.      * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 3
  72.      */
  73.     int count = 0;
  74.     /**
  75.      * TODO: definirajte gi potrebnite elementi za sinhronizacija
  76.      */
  77.  
  78.     //Monitor
  79.     final Object mutexCounterLock = new Object();
  80.  
  81.     public void init() {
  82.     }
  83.  
  84.     class Counter extends Thread {
  85.         public void count(int[] data) {
  86.             int localCount = 0;
  87.             for (int number : data) {
  88.                 if (number == 3) {
  89.                     localCount++;
  90.                     //Ako ne koristam lokalna promenliva, togas na sekoja
  91.                     //trojka vo nizata treba da gi blokiram drugite threadovi
  92.                     //ne e optimalno...
  93.                 }
  94.             }
  95.             synchronized (mutexCounterLock) {
  96.                 count += localCount;
  97.             }
  98.         }
  99.         private int[] data;
  100.  
  101.         /*
  102.         3 4 8 7 4 4 9 7 6 1 3 1 7 1 7 2 4 3 10 8 3 2 7 1 2 10 10 4 2 3 8 1 1 3 4 9 8 2 6 10 3 8 7 4 3 10 6 4 7 5 7 1 1 7 6 1 1 10 7 1 9 3 4 9 5 6 7 6 4 8 10 8 8 10 6 7 1 6 7 9 2 7 2 8 1 3 10 6 4 3 4 10 1 10 2 4 6 3 10 10
  103.         9 3 2 1 6 6 4 8 7 6 8 4 4 2 1 7 9 3 2 3 9 6 8 1 7 2 10 1 1 6 3 7 5 10 6 10 3 5 5 4 5 9 6 2 7 4 9 3 8 2 5 3 6 5 5 7 10 6 4 4 10 4 5 6 8 3 7 4 9 5 9 4 6 7 1 6 7 7 4 2 8 6 5 2 4 2 2 4 5 1 8 2 1 4 10 4 3 6 6 2
  104.         6 1 8 5 9 8 2 10 5 4 1 5 2 5 3 4 3 5 2 4 7 10 5 4 2 3 9 9 5 5 5 3 2 9 2 7 1 10 8 5 6 8 6 5 7 3 8 5 9 10 4 7 2 10 2 8 3 8 5 4 10 6 3 2 3 1 7 9 9 9 1 4 7 6 4 1 8 8 8 4 4 8 8 7 6 3 1 9 9 1 4 8 9 3 6 5 9 7 6 9 1
  105.         Se pojavuva tri pati
  106.          */
  107.  
  108.         public Counter(int[] data) {
  109.             this.data = data;
  110.         }
  111.  
  112.         @Override
  113.         public void run() {
  114.             try {
  115.                 count(data);
  116.             } catch (Exception e) {
  117.                 e.printStackTrace();
  118.             }
  119.         }
  120.     }
  121.  
  122.     public static void main(String[] args) {
  123.         try {
  124.             CountThree environment = new CountThree();
  125.             environment.start();
  126.         } catch (Exception ex) {
  127.             ex.printStackTrace();
  128.         }
  129.     }
  130.  
  131.     public void start() throws Exception {
  132.  
  133.         init();
  134.  
  135.         HashSet<Thread> threads = new HashSet<Thread>();
  136.         Scanner s = new Scanner(System.in);
  137.         int total=s.nextInt();
  138.  
  139.         for (int i = 0; i < NUM_RUNS; i++) {
  140.             int[] data = new int[total];
  141.             for (int j = 0; j < total; j++) {
  142.                 data[j] = s.nextInt();
  143.             }
  144.             Counter c = new Counter(data);
  145.             threads.add(c);
  146.         }
  147.  
  148.         for (Thread t : threads) {
  149.             t.start();
  150.         }
  151.  
  152.         for (Thread t : threads) {
  153.             t.join();
  154.         }
  155.         System.out.println(count);
  156.  
  157.  
  158.     }
  159. }
  160.  
  161.  
  162.  
  163.  
  164.  
  165. /*
  166. Task 3 Problem 1 (1 / 1)
  167. Implement the class FileScanner that will act as a thread. Inside the FileScanner class the following data are saved: - path to a directory that has to be scanned, - a static variable counter that will count the total number of threads that will be created. Implement a static method that will print the info for the file in the following format:
  168.  
  169. dir: C:\Users\185026\Desktop\lab1 - solutions 4096 (dir for directory, absolute path and size)
  170.  
  171. file: C:\Users\Stefan\Desktop\spisok.pdf 29198 (file for files, absolute path and size)
  172.  
  173. The run() method should be overridden in a way that it will print the information for the file that it is scanning. If the current directory has sub-directories, a new FileScanner thread should be started for each of these files, and will act the same as previously described (recursively)
  174.  
  175. When the entire directory tree is scanned, print the counter value:
  176. */
  177.  
  178. import java.io.*;
  179. import java.io.File;
  180. import java.util.HashSet;
  181.  
  182.  
  183. public class FileScanner extends Thread  {
  184.  
  185.     private String fileToScan;
  186.     //TODO: Initialize the start value of the counter
  187.     private static Long counter = 0L;
  188.  
  189.     public FileScanner (String fileToScan) {
  190.         //TODO: Increment the counter on every creation of FileScanner object
  191.         this.fileToScan=fileToScan;
  192.         synchronized(this) {
  193.             counter++;
  194.         }
  195.     }
  196.  
  197.     public static void printInfo(File file)  {
  198.         /*
  199.         * TODO: Print the info for the @argument File file, according to the requirement of the task
  200.         * */
  201.         if(file.isDirectory()) {
  202.             System.out.printf("dir: %s - solutions %d\n", file.getAbsolutePath(), getDirectorySize(file));
  203.         } else if(file.isFile()) {
  204.             System.out.printf("file: %s %d\n", file.getAbsolutePath(), file.length());
  205.         } else {
  206.             System.err.println("ERROR");
  207.         }
  208.     }
  209.  
  210.     public static long getDirectorySize(File f) {
  211.         if(!f.isDirectory())
  212.             return 0;
  213.  
  214.         long length = 0;
  215.  
  216.         for(File file : f.listFiles()) {
  217.             if(file.isFile())
  218.                 length+=file.length();
  219.             else if (file.isDirectory())
  220.                 length+=getDirectorySize(file);
  221.         }
  222.  
  223.         return length;
  224.     }
  225.  
  226.     public static Long getCounter () {
  227.         return counter;
  228.     }
  229.  
  230.  
  231.     public void run() {
  232.  
  233.         //TODO Create object File with the absolute path fileToScan.
  234.         File file = new File(fileToScan);
  235.  
  236.         //TODO Create a list of all the files that are in the directory file.
  237.         File [] files = file.listFiles();
  238.  
  239.         for (File f : files) {
  240.             /*
  241.             * TODO If the File f is not a directory, print its info using the function printInfo(f)
  242.             * */
  243.             if(!f.isDirectory()) printInfo(f);
  244.  
  245.             /*
  246.             * TODO If the File f is a directory, create a thread from type FileScanner and start it.
  247.             * */
  248.             if(f.isDirectory()) {
  249.                 FileScanner newDirectoryThread = new FileScanner(f.getAbsolutePath());
  250.                 newDirectoryThread.start();
  251.  
  252.                 //TODO: wait for all the FileScanner-s to finish
  253.                 try {
  254.                     newDirectoryThread.join();
  255.                     // Koga ke zavrsi newDirectoryThread, prodolzi...
  256.                     // Blokira se dodeka threadot od koj e povikan ne terminira
  257.                     // Moze i so HashMap da gi cuvas pa posle iteriraj niz site i .join na sekoe
  258.                 } catch (InterruptedException e) {
  259.                     e.printStackTrace();
  260.                 }
  261.             }
  262.         }
  263.  
  264.     }
  265.  
  266.     public static void main (String [] args) {
  267.         String FILE_TO_SCAN = "C:\\Users\\Woody's Laptop\\Desktop\\SI";
  268.  
  269.         //TODO Construct a FileScanner object with the fileToScan = FILE_TO_SCAN
  270.         FileScanner fileScanner = new FileScanner(FILE_TO_SCAN);
  271.  
  272.         //TODO Start the thread from type FileScanner
  273.         fileScanner.start();
  274.  
  275.         //TODO wait for the fileScanner to finish
  276.         try {
  277.             fileScanner.join();
  278.         } catch (InterruptedException e) {
  279.             e.printStackTrace();
  280.         }
  281.  
  282.         //TODO print a message that displays the number of thread that were created
  283.         System.out.println(getCounter());
  284.  
  285.     }
  286. }
  287.  
  288.  
  289.  
  290.  
  291.  
  292.  
  293. /*
  294. Task 4 Problem 1 (1 / 1)
  295. You need to make a Chat Room application, where multiple clients will be connected to a single server through TCP/IP connection, and will communicate between each other.
  296.  
  297. The server starts a separate thread for each incoming connection, thus handling the messages received from each client and sending them to the destination client. All open sockets are saved in a HashMap structure by the server, and when the client exits the room, the socket is removed as well.
  298.  
  299. Every client receives a unique ID number on creation. When it's initialized, it sends the initial message to the server by only communicating the ID. Then, the client may start sending messages to other clients in the chat room, by sending a message to the server in the following format:
  300.  
  301. MESSAGE:RECEIVER_ID
  302.  
  303. Example: The client with ID = 1 wants to send the message "Hello from client 1" to client with ID = 2. The message that will be sent to the server will be like the following:
  304.  
  305. "Hello from client 1:2"
  306.  
  307. The server, when receiving a message from the client, extracts the receiver's id from the received message, and redirects the message to the receive (To the appropriate socket)
  308.  
  309. The client closes the connection (Exits the chat room) by sending the message "END" to the server.
  310.  
  311. The starter code is available bellow.
  312. */
  313.  
  314. import java.io.*;
  315. import java.net.ServerSocket;
  316. import java.net.Socket;
  317. import java.util.HashMap;
  318. import java.util.Scanner;
  319.  
  320. public class TCPServer {
  321.     private ServerSocket server;
  322.     private HashMap<Integer, Socket> activeConnections;
  323.  
  324.     // todo: Get the required connection
  325.     public Socket getConnection(int id) {
  326.         return activeConnections.get(id);
  327.     }
  328.  
  329.     // todo: Add connected client to the hash map
  330.     void addConnection(int id, Socket connection) {
  331.         activeConnections.put(id, connection);
  332.     }
  333.  
  334.     synchronized void endConnection(int id){
  335.         activeConnections.remove(id);
  336.     }
  337.  
  338.     //todo: Initialize server
  339.     private TCPServer(int port) throws IOException {
  340.         this.server = new ServerSocket(port);
  341.         activeConnections = new HashMap<>();
  342.     }
  343.  
  344.     // todo: Handle server listening
  345.     // todo: For each connection, start a separate
  346.     // todo: thread (ServerWorkerThread) to handle the communication
  347.     private void listen() throws IOException {
  348.         System.out.println("Server started on port " + server.getLocalPort());
  349.         System.out.println("Listening...");
  350.  
  351.         while(true) {
  352.             try {
  353.                 Socket newClient = server.accept();
  354.                 new ServerWorkerThread(newClient, this).start();
  355.             } catch (IOException e) {
  356.                 System.out.println("I/O error: " + e);
  357.             }
  358.         }
  359.     }
  360.  
  361.     public static void main(String[] args) throws IOException {
  362.         // todo: Start server
  363.         TCPServer server = new TCPServer(9876);
  364.         server.listen();
  365.     }
  366. }
  367.  
  368. class ServerWorkerThread extends Thread {
  369.     private Socket clientConn;
  370.     private TCPServer server;
  371.  
  372.     ServerWorkerThread(Socket clientConn, TCPServer server) {
  373.         this.clientConn = clientConn;
  374.         this.server = server;
  375.     }
  376.  
  377.     @Override
  378.     public void run() {
  379.         // todo: Handle listening to messages
  380.         try {
  381.             BufferedReader in = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
  382.             int id = Integer.parseInt(in.readLine());
  383.             server.addConnection(id, clientConn);
  384.             System.out.println("New connection arrived (Client ID: " + id + ")");
  385.             String line;
  386.             while((line = in.readLine()) != null) {
  387.                 if(line.equals("END")) {
  388.                     server.endConnection(id);
  389.                     System.out.println("Connection terminated (Client ID: " + id + ")");
  390.                 } else {
  391.                     String[] parts = line.split(":");
  392.                     Socket destination  = server.getConnection(Integer.parseInt(parts[1]));
  393.                     BufferedWriter out = new BufferedWriter(new OutputStreamWriter(destination.getOutputStream()));
  394.                     out.write(parts[0] + '\n');
  395.                     out.flush();
  396.                 }
  397.             }
  398.         } catch (IOException e) {
  399.             e.printStackTrace();
  400.         }
  401.     }
  402. }
  403.  
  404. import java.io.*;
  405. import java.net.Socket;
  406. import java.util.Scanner;
  407.  
  408. public class ClientStarter {
  409.     private int ID;
  410.     //todo: init other required variables here
  411.     private Socket serverConn;
  412.     private BufferedWriter outStream;
  413.  
  414.     private ClientStarter(int id, String host, int port) throws IOException {
  415.         this.ID = id;
  416.         // todo: Connect to server and send client ID
  417.         this.serverConn = new Socket(host, port);
  418.  
  419.         System.out.println("(Client " + ID + "): Conntected to the server " + serverConn.getInetAddress());
  420.  
  421.         outStream = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
  422.         outStream.write(ID + "\n");
  423.         outStream.flush();
  424.  
  425.         // todo: Listen for incoming messages
  426.         listen();
  427.     }
  428.  
  429.     // todo: Implement the sending message mechanism
  430.     void sendMessage(int idReceiver, String message) throws IOException {
  431.         outStream.write(message + ":" + idReceiver + "\n");
  432.         outStream.flush();
  433.     }
  434.  
  435.     // todo: end communication - send END to server
  436.     private void endCommunication() throws IOException {
  437.         outStream.write("END" + "\n");
  438.         outStream.flush();
  439.         outStream.close();
  440.     }
  441.  
  442.     // todo: listen for incoming messages from the server.
  443.     // It should start a separate thread to handle listening
  444.     // and not block the execution
  445.     // Should start a new ClientStarterWorkerThread
  446.     private void listen() throws IOException {
  447.         new ClientStarterWorkerThread(ID, new DataInputStream(serverConn.getInputStream())).start();
  448.     }
  449.  
  450.     public static void main(String[] args) throws IOException, InterruptedException {
  451.         //todo: Initialize and start 3 clients
  452.  
  453.         ClientStarter client1 = new ClientStarter(1,"localhost",9876);
  454.         ClientStarter client2 = new ClientStarter(2,"localhost",9876);
  455.         ClientStarter client3 = new ClientStarter(3,"localhost",9876);
  456.  
  457.         // Simulate chat
  458.         client1.sendMessage(2, "Hello from client 1");
  459.         Thread.sleep(1000);
  460.         client2.sendMessage(3, "Hello from client 2");
  461.         Thread.sleep(1000);
  462.         client1.sendMessage(3, "Hello from client 1");
  463.         Thread.sleep(1000);
  464.         client3.sendMessage(1, "Hello from client 3");
  465.         Thread.sleep(1000);
  466.         client3.sendMessage(2, "Hello from client 3");
  467.  
  468.         // Exit the chatroom
  469.         client1.endCommunication();
  470.         client2.endCommunication();
  471.         client3.endCommunication();
  472.     }
  473. }
  474.  
  475. class ClientStarterWorkerThread extends Thread {
  476.     private int ID;
  477.     private DataInputStream inputStream;
  478.  
  479.     public ClientStarterWorkerThread(int clientID, DataInputStream inputStream) {
  480.         this.ID = clientID;
  481.         this.inputStream = inputStream;
  482.     }
  483.  
  484.     @Override
  485.     public void run() {
  486.         // todo: Handle listening to messages
  487.         Scanner sc = new Scanner(inputStream);
  488.         while(sc.hasNext()) {
  489.             System.out.println("(Receiver Client: " + ID + ") " + sc.nextLine());
  490.         }
  491.         sc.close();
  492.     }
  493. }
Advertisement
Add Comment
Please, Sign In to add comment