Advertisement
NikolaDimov

[OS] Lab2

Mar 30th, 2020
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.38 KB | None | 0 0
  1. /*
  2. Да се имплементира класа FileScanner која што ќе се однесува како thread. Во класата FileScanner се чуваат податоци за : - патеката на директориумот што треба да се скенира - статичка променлива counter што ќе брои колку нишки од класата FileScanner ќе се креираат Во класата FileScanner да се имплементираа статички методот што ќе печати информации за некоја датотека од следниот формат:
  3.  
  4. dir: C:\Users\185026\Desktop\lab1 - reshenija 4096 (dir за директориуми, апсолутна патека и големина)
  5.  
  6. file: C:\Users\Stefan\Desktop\spisok.pdf 29198 (file за обични фајлови, апсолутна патека и големина)
  7.  
  8. Дополнително да се преоптовари методот run() од класата Thread, така што ќе печати информации за директориумот за којшто е повикан. Доколку во директориумот има други под директориуми, да се креира нова нишка од тип FileScanner што ќе ги прави истите работи како и претходно за фајловите/директориумите што се наоѓаат во тие директориуми (рекурзивно).
  9.  
  10. На крај да се испечати вредноста на counter-от, односно колку вкупно нишки биле креирани.  Користете го следниот почетен код.
  11. */
  12.  
  13. public class FileScanner  {
  14.  
  15.     private String fileToScan;
  16.     //TODO: Initialize the start value of the counter
  17.     private static Long counter;
  18.  
  19.     public FileScanner (String fileToScan) {
  20.         this.fileToScan=fileToScan;
  21.         //TODO: Increment the counter on every creation of FileScanner object
  22.     }
  23.  
  24.     public static void printInfo(File file)  {
  25.  
  26.         /*
  27.         * TODO: Print the info for the @argument File file, according to the requirement of the task
  28.         * */
  29.  
  30.     }
  31.  
  32.     public static Long getCounter () {
  33.         return counter;
  34.     }
  35.  
  36.  
  37.     public void run() {
  38.  
  39.         //TODO Create object File with the absolute path fileToScan.
  40.         File file;
  41.  
  42.         //TODO Create a list of all the files that are in the directory file.
  43.         File [] files = null;
  44.  
  45.  
  46.         for (File f : files) {
  47.  
  48.             /*
  49.             * TODO If the File f is not a directory, print its info using the function printInfo(f)
  50.             * */
  51.  
  52.             /*
  53.             * TODO If the File f is a directory, create a thread from type FileScanner and start it.
  54.             * */
  55.  
  56.             //TODO: wait for all the FileScanner-s to finish
  57.         }
  58.  
  59.     }
  60.  
  61.     public static void main (String [] args) {
  62.         String FILE_TO_SCAN = "C:\\Users\\189075\\Desktop\\lab";
  63.  
  64.         //TODO Construct a FileScanner object with the fileToScan = FILE_TO_SCAN
  65.         FileScanner fileScanner;
  66.  
  67.         //TODO Start the thread from type FileScanner
  68.  
  69.         //TODO wait for the fileScanner to finish
  70.  
  71.         //TODO print a message that displays the number of thread that were created
  72.  
  73.  
  74.     }
  75. }
  76.  
  77. ===================================######################################====================================
  78. ===================================######################################====================================
  79.  
  80. /*
  81. Со помош на синхронизациските методи да се реши проблемот за определување на бројот на појавувања на бројот 7 во огромна низа и негово запишување во глобална променлива count.
  82.  
  83. Секвенцијалното решение не е прифатливо поради тоа што трае многу долго време (поради големината на низата). За таа цел, потребно е да се паралелизира овој процес, при што треба да се напише метода која ќе ги брои појавувањата на бројот 7 во помал фрагмент од низата, при што резултатот повторно се чува во глобалната заедничка променлива count.
  84.  
  85. Напомена: Почетниот код е даден во почетниот код CountSeven. Задачата да се тестира над низа од минимум 1000 елементи.
  86. */
  87.  
  88. public class CountSeven {
  89.  
  90.     public static int NUM_RUNS = 100;
  91.     /**
  92.      * Promenlivata koja treba da go sodrzi brojot na pojavuvanja na elementot 7
  93.      */
  94.     int count = 0;
  95.     /**
  96.      * TODO: definirajte gi potrebnite elementi za sinhronizacija
  97.      */
  98.  
  99.     public void init() {
  100.     }
  101.  
  102.     class Counter extends Thread {
  103.  
  104.         public void count(int[] data) throws InterruptedException {
  105.             // da se implementira
  106.         }
  107.         private int[] data;
  108.  
  109.         public Counter(int[] data) {
  110.             this.data = data;
  111.         }
  112.  
  113.         @Override
  114.         public void run() {
  115.             try {
  116.                 count(data);
  117.             } catch (Exception e) {
  118.                 e.printStackTrace();
  119.             }
  120.         }
  121.     }
  122.  
  123.     public static void main(String[] args) {
  124.         try {
  125.             CountSeven environment = new CountSeven();
  126.             environment.start();
  127.         } catch (Exception ex) {
  128.             ex.printStackTrace();
  129.         }
  130.     }
  131.  
  132.     public void start() throws Exception {
  133.  
  134.         init();
  135.  
  136.         HashSet<Thread> threads = new HashSet<Thread>();
  137.         Scanner s = new Scanner(System.in);
  138.         int total=s.nextInt();
  139.  
  140.         for (int i = 0; i < NUM_RUNS; i++) {
  141.             int[] data = new int[total];
  142.             for (int j = 0; j < total; j++) {
  143.                 data[j] = s.nextInt();
  144.             }
  145.             Counter c = new Counter(data);
  146.             threads.add(c);
  147.         }
  148.  
  149.         for (Thread t : threads) {
  150.             t.start();
  151.         }
  152.  
  153.         for (Thread t : threads) {
  154.             t.join();
  155.         }
  156.         System.out.println(count);
  157.  
  158.  
  159.     }
  160. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement