Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Task 1 Problem 1 (1 / 1)
- 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.
- 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?
- */
- public class TwoThreads {
- // public static class Thread1 extends Thread {
- // public void run() {
- // System.out.println("A");
- // System.out.println("B");
- // }
- // }
- //
- // public static class Thread2 extends Thread {
- // public void run() {
- // System.out.println("1");
- // System.out.println("2");
- // }
- // }
- public static class ThreadAB implements Runnable {
- String[] str;
- ThreadAB(String... str) {
- this.str = str;
- }
- @Override
- public void run() {
- for(String string : str) {
- System.out.println(string);
- }
- }
- }
- public static void main(String[] args) {
- // new Thread1().start();
- // new Thread2().start();
- //Thread() konstruktorot prima Runnable objekti
- Thread threadAlphabet = new Thread(new ThreadAB("A", "B", "C", "D", "E", "F", "G", "H"));
- Thread threadNumbers = new Thread(new ThreadAB("1", "2", "3", "4", "5", "6", "7"));
- threadAlphabet.start();
- threadNumbers.start();
- //Outputot nemoze da se predvidi, se izvrsuvaat "paralelno"
- }
- }
- /*
- Task 2 Problem 1 (1 / 1)
- 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.
- 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.
- 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.
- */
- import java.util.HashSet;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- public class CountThree {
- public static int NUM_RUNS = 100;
- /**
- * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 3
- */
- int count = 0;
- /**
- * TODO: definirajte gi potrebnite elementi za sinhronizacija
- */
- //Monitor
- final Object mutexCounterLock = new Object();
- public void init() {
- }
- class Counter extends Thread {
- public void count(int[] data) {
- int localCount = 0;
- for (int number : data) {
- if (number == 3) {
- localCount++;
- //Ako ne koristam lokalna promenliva, togas na sekoja
- //trojka vo nizata treba da gi blokiram drugite threadovi
- //ne e optimalno...
- }
- }
- synchronized (mutexCounterLock) {
- count += localCount;
- }
- }
- private int[] data;
- /*
- 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
- 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
- 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
- Se pojavuva tri pati
- */
- public Counter(int[] data) {
- this.data = data;
- }
- @Override
- public void run() {
- try {
- count(data);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- try {
- CountThree environment = new CountThree();
- environment.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public void start() throws Exception {
- init();
- HashSet<Thread> threads = new HashSet<Thread>();
- Scanner s = new Scanner(System.in);
- int total=s.nextInt();
- for (int i = 0; i < NUM_RUNS; i++) {
- int[] data = new int[total];
- for (int j = 0; j < total; j++) {
- data[j] = s.nextInt();
- }
- Counter c = new Counter(data);
- threads.add(c);
- }
- for (Thread t : threads) {
- t.start();
- }
- for (Thread t : threads) {
- t.join();
- }
- System.out.println(count);
- }
- }
- /*
- Task 3 Problem 1 (1 / 1)
- 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:
- dir: C:\Users\185026\Desktop\lab1 - solutions 4096 (dir for directory, absolute path and size)
- file: C:\Users\Stefan\Desktop\spisok.pdf 29198 (file for files, absolute path and size)
- 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)
- When the entire directory tree is scanned, print the counter value:
- */
- import java.io.*;
- import java.io.File;
- import java.util.HashSet;
- public class FileScanner extends Thread {
- private String fileToScan;
- //TODO: Initialize the start value of the counter
- private static Long counter = 0L;
- public FileScanner (String fileToScan) {
- //TODO: Increment the counter on every creation of FileScanner object
- this.fileToScan=fileToScan;
- synchronized(this) {
- counter++;
- }
- }
- public static void printInfo(File file) {
- /*
- * TODO: Print the info for the @argument File file, according to the requirement of the task
- * */
- if(file.isDirectory()) {
- System.out.printf("dir: %s - solutions %d\n", file.getAbsolutePath(), getDirectorySize(file));
- } else if(file.isFile()) {
- System.out.printf("file: %s %d\n", file.getAbsolutePath(), file.length());
- } else {
- System.err.println("ERROR");
- }
- }
- public static long getDirectorySize(File f) {
- if(!f.isDirectory())
- return 0;
- long length = 0;
- for(File file : f.listFiles()) {
- if(file.isFile())
- length+=file.length();
- else if (file.isDirectory())
- length+=getDirectorySize(file);
- }
- return length;
- }
- public static Long getCounter () {
- return counter;
- }
- public void run() {
- //TODO Create object File with the absolute path fileToScan.
- File file = new File(fileToScan);
- //TODO Create a list of all the files that are in the directory file.
- File [] files = file.listFiles();
- for (File f : files) {
- /*
- * TODO If the File f is not a directory, print its info using the function printInfo(f)
- * */
- if(!f.isDirectory()) printInfo(f);
- /*
- * TODO If the File f is a directory, create a thread from type FileScanner and start it.
- * */
- if(f.isDirectory()) {
- FileScanner newDirectoryThread = new FileScanner(f.getAbsolutePath());
- newDirectoryThread.start();
- //TODO: wait for all the FileScanner-s to finish
- try {
- newDirectoryThread.join();
- // Koga ke zavrsi newDirectoryThread, prodolzi...
- // Blokira se dodeka threadot od koj e povikan ne terminira
- // Moze i so HashMap da gi cuvas pa posle iteriraj niz site i .join na sekoe
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- public static void main (String [] args) {
- String FILE_TO_SCAN = "C:\\Users\\Woody's Laptop\\Desktop\\SI";
- //TODO Construct a FileScanner object with the fileToScan = FILE_TO_SCAN
- FileScanner fileScanner = new FileScanner(FILE_TO_SCAN);
- //TODO Start the thread from type FileScanner
- fileScanner.start();
- //TODO wait for the fileScanner to finish
- try {
- fileScanner.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //TODO print a message that displays the number of thread that were created
- System.out.println(getCounter());
- }
- }
- /*
- Task 4 Problem 1 (1 / 1)
- 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.
- 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.
- 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:
- MESSAGE:RECEIVER_ID
- 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:
- "Hello from client 1:2"
- 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)
- The client closes the connection (Exits the chat room) by sending the message "END" to the server.
- The starter code is available bellow.
- */
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.HashMap;
- import java.util.Scanner;
- public class TCPServer {
- private ServerSocket server;
- private HashMap<Integer, Socket> activeConnections;
- // todo: Get the required connection
- public Socket getConnection(int id) {
- return activeConnections.get(id);
- }
- // todo: Add connected client to the hash map
- void addConnection(int id, Socket connection) {
- activeConnections.put(id, connection);
- }
- synchronized void endConnection(int id){
- activeConnections.remove(id);
- }
- //todo: Initialize server
- private TCPServer(int port) throws IOException {
- this.server = new ServerSocket(port);
- activeConnections = new HashMap<>();
- }
- // todo: Handle server listening
- // todo: For each connection, start a separate
- // todo: thread (ServerWorkerThread) to handle the communication
- private void listen() throws IOException {
- System.out.println("Server started on port " + server.getLocalPort());
- System.out.println("Listening...");
- while(true) {
- try {
- Socket newClient = server.accept();
- new ServerWorkerThread(newClient, this).start();
- } catch (IOException e) {
- System.out.println("I/O error: " + e);
- }
- }
- }
- public static void main(String[] args) throws IOException {
- // todo: Start server
- TCPServer server = new TCPServer(9876);
- server.listen();
- }
- }
- class ServerWorkerThread extends Thread {
- private Socket clientConn;
- private TCPServer server;
- ServerWorkerThread(Socket clientConn, TCPServer server) {
- this.clientConn = clientConn;
- this.server = server;
- }
- @Override
- public void run() {
- // todo: Handle listening to messages
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
- int id = Integer.parseInt(in.readLine());
- server.addConnection(id, clientConn);
- System.out.println("New connection arrived (Client ID: " + id + ")");
- String line;
- while((line = in.readLine()) != null) {
- if(line.equals("END")) {
- server.endConnection(id);
- System.out.println("Connection terminated (Client ID: " + id + ")");
- } else {
- String[] parts = line.split(":");
- Socket destination = server.getConnection(Integer.parseInt(parts[1]));
- BufferedWriter out = new BufferedWriter(new OutputStreamWriter(destination.getOutputStream()));
- out.write(parts[0] + '\n');
- out.flush();
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- import java.io.*;
- import java.net.Socket;
- import java.util.Scanner;
- public class ClientStarter {
- private int ID;
- //todo: init other required variables here
- private Socket serverConn;
- private BufferedWriter outStream;
- private ClientStarter(int id, String host, int port) throws IOException {
- this.ID = id;
- // todo: Connect to server and send client ID
- this.serverConn = new Socket(host, port);
- System.out.println("(Client " + ID + "): Conntected to the server " + serverConn.getInetAddress());
- outStream = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
- outStream.write(ID + "\n");
- outStream.flush();
- // todo: Listen for incoming messages
- listen();
- }
- // todo: Implement the sending message mechanism
- void sendMessage(int idReceiver, String message) throws IOException {
- outStream.write(message + ":" + idReceiver + "\n");
- outStream.flush();
- }
- // todo: end communication - send END to server
- private void endCommunication() throws IOException {
- outStream.write("END" + "\n");
- outStream.flush();
- outStream.close();
- }
- // todo: listen for incoming messages from the server.
- // It should start a separate thread to handle listening
- // and not block the execution
- // Should start a new ClientStarterWorkerThread
- private void listen() throws IOException {
- new ClientStarterWorkerThread(ID, new DataInputStream(serverConn.getInputStream())).start();
- }
- public static void main(String[] args) throws IOException, InterruptedException {
- //todo: Initialize and start 3 clients
- ClientStarter client1 = new ClientStarter(1,"localhost",9876);
- ClientStarter client2 = new ClientStarter(2,"localhost",9876);
- ClientStarter client3 = new ClientStarter(3,"localhost",9876);
- // Simulate chat
- client1.sendMessage(2, "Hello from client 1");
- Thread.sleep(1000);
- client2.sendMessage(3, "Hello from client 2");
- Thread.sleep(1000);
- client1.sendMessage(3, "Hello from client 1");
- Thread.sleep(1000);
- client3.sendMessage(1, "Hello from client 3");
- Thread.sleep(1000);
- client3.sendMessage(2, "Hello from client 3");
- // Exit the chatroom
- client1.endCommunication();
- client2.endCommunication();
- client3.endCommunication();
- }
- }
- class ClientStarterWorkerThread extends Thread {
- private int ID;
- private DataInputStream inputStream;
- public ClientStarterWorkerThread(int clientID, DataInputStream inputStream) {
- this.ID = clientID;
- this.inputStream = inputStream;
- }
- @Override
- public void run() {
- // todo: Handle listening to messages
- Scanner sc = new Scanner(inputStream);
- while(sc.hasNext()) {
- System.out.println("(Receiver Client: " + ID + ") " + sc.nextLine());
- }
- sc.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment