» נושאי לימוד
» נושאי לימוד
יום שני 29 באפריל 2024
שו"ת - חזרה
דף ראשי  מתקדמים  Treads of control  שו"ת - חזרה גרסה להדפסה

שו"ת - חזרה על החומר

 

ש מה ההגדרה לתיכנות שהוא multithreaded לפי Patrick Naughton?

ת- לפי הספר “The Java Ahndbook” מאת Patrick Naughton, "תכנות שהוא multithreaded הוא תבנית רעיונית לתיכנות שבה אתה מחלק תוכניות לשני תהליכים או יותר שיכולים להיות מורצים בו-זמנית".

 

ש- Multithreading  מתייחס לשתי תוכניות או יותר הפועלות "לכאורה"' בו זמנית, תחת בקרה של מערכת ההפעלה. אין צורך שיהיה שום קשר בין התוכניות מלבד העובדה שאתה רוצה להתחיל להריץ את כולן בו-זמנית. נכון או לא נכון? אם לא נכון הסבר מדוע.   

ת- לא נכון. זה  תיאור של multiprocessing , לא של multithreading. Multithreading מתייחס לשני tasks או יותר הפועלות "לכאורה" במקביל בתוך תוכנית אחת.

 

ש- לפי המינוח העכשווי, המונח  blocked פירושו שה thread מחכה שמשהו יקרה ולא צורך משאבי מחשב. נכון או לא נכון? אם לא נכון הסבר מדוע.

ת- נכון.

 

ש- מהן שתי הדרכים ליצור תוכניות שהן threaded בג'אווה?

ת- בג'אווה יש שתי דרכים ליצור תוכניות שהן  threaded :

 ·         ליישם את הממשק הניתן להרצה.

 ·         לירוש מהמחלקה Thread

 

ש- מהם שני הצעדים שנדרשים לייצור של  thread  בג'אווה?

ת- שני הצעדים שחייבם לבצע בכדי לייצר thread בג'אווה הם:

 ·          ליצור מופע לאובייקט מסוג Thread   ו-

 ·     להפעיל את מתודת ה()run  שלו.

 

ש- איך אתה מתחיל הרצה ממשית שלthread  בג'אווה?

ת- מפעיל את המתודה start() על אובייקט של המחלקה Thread או של מחלקת משנה של מחלקת Thread.

 

ש- תמיד ניתן להרחיב את (לירוש מ-) מהמחלקה Thread בייישומי הג'אווה והתוכניות הקטנות (applets) שלך. נכון או לא נכון. אם לא נכון, הסבר מדוע.

ת- לפעמים לא ניתן לירוש מהמחלקה Thread  מכיוון שאתה חייב לירוש ממחלקה אחרת וג'אווה אינה תומכת בירושה מרובה.

 

ש- למרות שתיכנות שהוא multithreaded  אפשרי בג'אווה, ניתן גם לכתוב תוכניות ג'אווה שאינן מערבות threads : נכון או לא נכון? אם לא נכון, הסבר מדוע.

ת- לא נכון. המתודה main בעצמה רצה ב thread  שמפעיל ה interpreter .

 

ש- מה שם המתודה בה ניתן להשתמש בכדי לקבוע אם thread  מסוים חי?

ת- שם המתודה הוא isAlive().

 

ש- ברגע שהתחלת להריץ שני threads  או יותר, עד שלא תגדיר אחרת, הם ירוצו באופן מסונכרן ובלתי תלוי אחד בשני. נכון או לא נכון? אם לא נכון, הסבר מדוע.

ת- לא נכון. ברגע שהתחלת להריץ threads , עד שלא תגדיר אחרת, הם ירוצו באופן בלתי מסונכרן (asynchronously) ובלתי תלוי אחד בשני.

 

ש- התהליך ששומר ש thread   אחד לא יקלקל נתונים בזמן שהם מעובדים על ידי thread אחר ידוע בשם סנכרון: נכון או לא נכון? אם לא נכון, הסבר מדוע.

ת- נכון.

 

ש- ג'אווה מאפשרת לך לקבוע את דרגת העדיפות המוחלטת של כל אחד מה threads. נכון או לא נכון? אם לא נכון הסבר מדוע.

ת- לא נכון. ג'אווה מאפשרת לך לקבוע את דרגת העדיפות של כל thread  ביחס לשאר ה threads  אבל לא על באופן מוחלט.

 

ש- אפשר לבצע סנכרון של threads  בעזרת שימוש ב wait(), notify(), וב notifyAll() שהן מתודות של המחלקה Thread. נכון או לא נכון? אם לא נכון, הסבר מדוע.

ת- לא נכון. wait(), notify() ו- notifyAll אינן מתודות של המחלקה Thread אלא של המחלקה Object.

 

ש- כשאתה מיישם תוכנית שהיא threaded , אתה תמיד צריך לדרוס את המתודה של המחלקה Thread  ולדאוג שהפונקציונליות של התוכנית ה threaded שלך תהיה מובנת בתוך המתודה הזו. מה שם המתודה?

ת- המתודה run().

 

ש- בתוכנית שהיא multithreaded , תתחיל הרצה של thread על ידי הפעלת המתודה על אובייקט ה Thread שלך שבתגובה יפעיל את המתודה             . מה שמות המתודות החסרות, ומה הם הפרמטרים הנדרשים עבור כל אחת מהמתודות?

  ת- בתוכנית שהיא multithreaded , תתחיל להריץ thread על ידי הפעלת מתודת start() על אובייקט ה Thread שלך שבתגובה יפעיל את המתודה run(). אף אחת מהן לא נזקקת לשום פרמטרים.

 

ש- אילו ארבעה מצבים אפשריים של thread מונים Campione & Walrath ?

ת- Campione & Walrath  מונים את ארבעת המצבים האפשריים הבאים:

 ·           חדש (New Thread)

 ·           ניתן להרצה(Runnable)

 ·           לא ניתן להרצה (Not Runnable)      

 ·           מת (Dead)   

 

ש- אילו מתודות להפעיל על אובייקט thread הנמצא במצב שCampione & Walrath      מגדירים כ thread  חדש (New Thread) ומה יקרה אם תפעיל מתודה אחרת כל שהיא על ה thread?

ת- כש thread  נמצא במצב הזה, אתה יכול רק או להפעיל את ה thread או לעצור אותו. קריאה למתודה שונה מלבד start()  או stop() תגרום ל IllegalThreadStateException.

 

ש- מה לפי Campione & Walrath יגרום ל thread  להיהפך לבלתי ניתן להרצה

 (Not Runnable)?

ת- לפי Campione & Walrath , thread הופך לבלתי ניתן להרצה כשמתרחש אחד המצבים הבאים:

 ·          מישהו מפעיל את מתודת ה()run   שלו.

 ·  מישהו מפעיל את מתודת ה()suspend שלו.

 ·           thread משתמש במתודת ה wait() שלו לחכות במשתנה תנאי

 ·          הthread   חוסם את is blocking on) I/O).

 

ש- כתוב תוכנית שעונה על ההגדרות הבאות.

/*File SampProg104.java from lesson 58
Copyright 1997, R.G.Baldwin
Without viewing the solution that follows, write a Java
application that illustrates the instantiation and running 
of two threads by implementing the runnable interface (as
opposed to extending the Thread class).

Use a version of constructor that allows you to specify
a name for the new thread.

The output displays information about the running threads
and should be similar to the following:
  
Thread[threadA,5,main]
Thread[threadB,5,main]
Thread[main,5,main]
===========================================================
*/

class SampProg104{
  static public void main(String[] args){
    //Instantiate two new thread objects
    Thread threadA = new Thread(new MyThread(),"threadA");
    Thread threadB = new Thread(new MyThread(),"threadB");

    //Start them running
    threadA.start();
    threadB.start();
    
    try{
      Thread.currentThread().sleep(1000);//delay one second
    }catch(InterruptedException e){}

    //Display info about the main thread    
    System.out.println(Thread.currentThread());        

    //stop the two threads which were started above
    threadA.stop();
    threadB.stop();
  }//end main
}//end class SampProg104

class MyThread implements Runnable{
  public void run(){//override run method
    //Display info about this particular thread
    System.out.println(Thread.currentThread());
  }//end run
}//end class MyThread

 

ש- כתוב תוכנית שעונה על ההגדרות הבאות.

/*File SampProg105.java  from lesson 58
Copyright 1997, R.G.Baldwin
Without viewing the solution that follows, write a Java
application that illustrates the instantiation and running 
of two threads by extending the Thread class (as opposed
to implementing the Runnable class).

Use a version of constructor that allows you to specify
a name for the new thread.

The output should display information about the running
threads and should be similar to the following:
  
Thread[threadA,5,main]
Thread[threadB,5,main]
Thread[main,5,main]
===========================================================
*/

class SampProg105{
  static public void main(String[] args){
    //Instantiate two new thread objects
    Thread threadA = new Thread(new MyThread(),"threadA");
    Thread threadB = new Thread(new MyThread(),"threadB");

    //Start them running
    threadA.start();
    threadB.start();
    
    try{
      Thread.currentThread().sleep(1000);//delay one second
    }catch(InterruptedException e){}

    //Display info about the main thread    
    System.out.println(Thread.currentThread());        

    //stop the two threads which were started above
    threadA.stop();
    threadB.stop();
  }//end main
}//end class SampProg105

class MyThread extends Thread{
  public void run(){//override run method
    //Display info about this particular thread
    System.out.println(Thread.currentThread());
  }//end run
}//end class MyThread

 

ש- כתוב תוכנית שעונה על ההגדרות הבאות.

/*File SampProg106.java from lesson 58
Copyright 1997, R.G.Baldwin
Without viewing the solution that follows, write a Java
application that illustrates the instantiation and running
of two threads by extending the Thread class.

Use a version of the thread constructor that doesn't
take any arguments.

The output should be similar to the following:
Thread[Thread-1,5,main]
Thread[Thread-2,5,main]
Thread[main,5,main]
===========================================================
*/

class SampProg106{
  static public void main(String[] args){
    //Instantiate two new thread objects
    Thread threadA = new MyThread();
    Thread threadB = new MyThread();

    //Start them running
    threadA.start();
    threadB.start();
    
    try{
      Thread.currentThread().sleep(1000);//delay one second
    }catch(InterruptedException e){}

    //Display info about the main thread    
    System.out.println(Thread.currentThread());        

    //stop the two threads which were started above
    threadA.stop();
    threadB.stop();
  }//end main
}//end class SampProg106

class MyThread extends Thread{
  public void run(){
    //Display info about this particular thread
    System.out.println(Thread.currentThread());
  }//end run
}//end class MyThread

 

ש- כתוב תוכנית שעונה על ההגדרות הבאות.

/*File SampProg107.java from lesson 58
Copyright 1997, R.G.Baldwin
Without viewing the solution that follows, write a Java
application that illustrates the instantiation and running 
of two threads using the runnable interface.  Cause each of
two threads to count from zero to four, displaying the 
count, and sleeping a random amount of time between counts.

The output should be similar to the following:

Thread[thrdA,5,main] cnt is 0
Thread[threadB,5,main] cnt is 0
Thread[threadB,5,main] cnt is 1
Thread[threadB,5,main] cnt is 2
Thread[thrdA,5,main] cnt is 1
Thread[thrdA,5,main] cnt is 2
Thread[threadB,5,main] cnt is 3
Thread[thrdA,5,main] cnt is 3
Thread[threadB,5,main] cnt is 4
Thread[thrdA,5,main] cnt is 4
===========================================================
*/

class SampProg107{
  static public void main(String[] args){
    //Instantiate two new thread objects with names of 
    // different lengths which helps when viewing the 
    // output.
    Thread threadA = new Thread(new MyThread(),"thrdA");
    Thread threadB = new Thread(new MyThread(),"threadB");

    //Start them running
    threadA.start();
    threadB.start();
    
    try{
      Thread.currentThread().sleep(1000);//delay one second
    }catch(InterruptedException e){}

    //stop the two threads which were started above
    threadA.stop();
    threadB.stop();
  }//end main
}//end class SampProg107


class MyThread implements Runnable{
  public void run(){//override the run method
    for(int cnt = 0; cnt < 5; cnt++){
      System.out.println(Thread.currentThread() 
        + " cnt is " + cnt);
      try{//delay a random amount of time
        Thread.currentThread().sleep(
          (int)(Math.random() * 100));
      }catch(InterruptedException e){}
    }//end for-loop
  }//end run
}//end class MyThread
//end program

 

ש- כתוב תוכנית שעונה על ההגדרות הבאות.

/*File SampProg108.java from lesson 58
Copyright 1997, R.G.Baldwin
Without viewing the solution that follows, write a Java
application that illustrates the instantiation and running
of four different threads using the runnable interface 
where two different thread classes are defined each of 
which uses the Runnable interface.  The run() method in one
class is different from the run() method in the other 
class.

Two Thread objects are instantiated and started for each of
the two thread classes, resulting in four different threads
running.

Each of the threads counts from zero to four and displays 
the count, sleeping a random amount of time between counts.
Make the format of the display different between the two 
thread classes.

The output should be similar to the following:
  

Thread[thrdA,5,main] cnt is 0
Thread[threadB,5,main] cnt is 0
The actual cnt is 0 Thread[Xthrd,5,main]
The actual cnt is 0 Thread[Ythread,5,main]
Thread[thrdA,5,main] cnt is 1
Thread[threadB,5,main] cnt is 1
Thread[thrdA,5,main] cnt is 2
The actual cnt is 1 Thread[Ythread,5,main]
The actual cnt is 1 Thread[Xthrd,5,main]
Thread[threadB,5,main] cnt is 2
The actual cnt is 2 Thread[Ythread,5,main]
Thread[thrdA,5,main] cnt is 3
The actual cnt is 3 Thread[Ythread,5,main]
Thread[thrdA,5,main] cnt is 4
The actual cnt is 2 Thread[Xthrd,5,main]
The actual cnt is 4 Thread[Ythread,5,main]
Thread[threadB,5,main] cnt is 3
The actual cnt is 3 Thread[Xthrd,5,main]
The actual cnt is 4 Thread[Xthrd,5,main]
Thread[threadB,5,main] cnt is 4
===========================================================
*/

class SampProg108{
  static public void main(String[] args){
    //Instantiate two new thread objects of one type
    Thread threadA = new Thread(
      new OneThreadClass(),"thrdA");
    Thread threadB = new Thread(
      new OneThreadClass(),"threadB");
    
    //Instantiate two new thread objects on another type
    Thread Xthread = new Thread(
      new AnotherThreadClass(),"Xthrd");
    Thread Ythread = new Thread(
      new AnotherThreadClass(),"Ythread");    

    //Start them running
    threadA.start();
    threadB.start();
    Xthread.start();
    Ythread.start();
    
    try{
      Thread.currentThread().sleep(1000);//delay one second
    }catch(InterruptedException e){}

    //stop the four threads which were started above
    threadA.stop();
    threadB.stop();
    Xthread.stop();
    Ythread.stop();
  }//end main
}//end class SampProg108


class OneThreadClass implements Runnable{
  public void run(){
    for(int cnt = 0; cnt < 5; cnt++){
      System.out.println(Thread.currentThread() 
        + " cnt is " + cnt);
      try{//delay a random amount of time
        Thread.currentThread().sleep(
          (int)(Math.random() * 100));
      }catch(InterruptedException e){}
    }//end for-loop
  }//end run
}//end class OneThreadClass

class AnotherThreadClass implements Runnable{
  public void run(){
    for(int cnt = 0; cnt < 5; cnt++){
      System.out.println("The actual cnt is " 
        + cnt + " " + Thread.currentThread());
      try{//delay a random amount of time
        Thread.currentThread().sleep(
          (int)(Math.random() * 100));
      }catch(InterruptedException e){}
    }//end for-loop
  }//end run
}//end class AnotherThreadClass
//end program

ש- כתוב תוכנית שעונה על ההגדרות הבאות.

/*File SampProg109.java from lesson 58
Copyright 1997, R.G.Baldwin
Without viewing the solution that follows, write a Java
application that illustrates thread synchronization by
implementing the Producer/Consumer model using wait() 
and notify().

Then view the following solution and compare it with your
solution to confirm that you have properly synchronized
your threads using the Producer/Consumer model.

**********************************************************/

class SampProg109{
  //instantiate a class object named QueueManager which 
  // will manage the producer/consumer model.
  static QueueManager queueManager = new QueueManager();
  //Following variable is used later to to tell the 
  // threads to terminate
  static boolean running = true;
  
  public static void main(String[] args){
    //instantiate and start two threads
    Thread producer = new Producer();
    Thread consumer = new Consumer();
    producer.start();    
    consumer.start();
    
    try{ 
      Thread.currentThread().sleep(2000);//delay two sec
    }catch(InterruptedException e){};

    running = false;//signal the threads to terminate
    
  }//end main

}//end class SampProg109
========================================================//

class Producer extends Thread { //producer thread
  public void run() { //override run method 
    byte byteToStore; //used to store data to be enqueued
    //loop until running goes false
    while (SampProg109.running) {
      byteToStore = (byte)(Math.random()*128);//get data
      //Invoke the synchronized method to put the byte 
      // in the queue        
      SampProg109.queueManager.putByteInQueue(
        byteToStore);
      //delay a random period of time
      try{ 
        Thread.currentThread().sleep(
          (int)(Math.random()*100));
      }catch(InterruptedException e){};
    }//end while statement
    System.out.println(
      "Terminating Producer run method");
  }//end run method
}//end class producer  
=========================================================//

class Consumer extends Thread { //consumer thread
  public void run() { //override run method
    //Variable used to store the data read from the queue
    byte dataFromQueue; 
    //loop until running goes false 
    while (SampProg109.running) {            
      //Invoke the synchronized method to get a byte from
      // the queue        
      dataFromQueue = 
        SampProg109.queueManager.getByteFromQueue();
      //delay a random amount of time
      try{ Thread.currentThread().sleep(
        (int)(Math.random()*100));
      }catch(InterruptedException e){};
    }//end while statement
    System.out.println("Terminating Consumer run method");
  }//end run method
}//end class consumer  
=========================================================//

//This class implements the Producer/Consumer model by 
// managing a queue as a shared resource.  
class QueueManager{
  Queue queue;
 
  QueueManager(){//constructor
    queue = new Queue();//instantiate a queue object
  }//end constructor

  synchronized void putByteInQueue(byte incomingByte){
    //This synchronized method places a byte in the queue
    // If the queue is full, wait(). If still full when 
    // wait() terminates, wait again. Called by the 
    // producer thread to put a byte in the queue.
    try{
      while(queue.isFull()){
        System.out.println("Queue full, waiting");
        wait();
      }//end while loop
    }catch (InterruptedException E){
      System.out.println("InterruptedException: " + E);
    }//end catch
    //put the byte into the queue
    queue.enQueue(incomingByte);
    
    //Wake up getByteFromQueue() if it has invoked wait().
    notify();
  }//end method putByteInQueue()
--------------------------------//
  public synchronized byte getByteFromQueue(){
    //This synchronized method removes a byte from the 
    // queue. If the queue is empty, wait(). If still 
    // empty when wait() terminates, wait again. Called by
    // consumer thread to get a byte from the queue
    try{
      while(queue.isEmpty()){
        System.out.println("Queue empty, waiting");
        wait();
      }// end while
    }catch (InterruptedException E){
      System.out.println("InterruptedException: " + E);
    }//end catch
    
    //get the byte from the queue
    byte data = queue.deQueue();
    
    //Wake up putByteInQueue() if it has invoked wait().
    notify();
    return data;
  }//end getByteFromQueue()
}//end class QueueManager  
=========================================================//

//This is a standard FIFO queue class.
class Queue{
  //constant defining maximum queue size
  static final int MAXQUEUE = 4;
  byte[] queue = new byte[MAXQUEUE];
  int front, rear;
    
  Queue(){//constructor
    front = rear = 0;
  }//end constructor
    
  void enQueue(byte item){
    queue[rear] = item;
    rear = next(rear);
  }//end method enQueue
   
  byte deQueue(){
    byte temp = queue[front];
    front = next(front);
    return temp;
  }//end method deQueue

  boolean isEmpty(){
    return front == rear;
  }//end isEmpty
    
  boolean isFull(){
    return (next(rear) == front);
  }//end isFull
    
  int next(int index){
    return (index+1 < MAXQUEUE ? index+1 : 0);
  }//end next

}//end Queue class
=========================================================//

 04-10-03 / 22:20  עודכן ,  04-10-03 / 15:33  נוצר ע"י רונית רייכמן  בתאריך 
 תוכנית סנכרון - הקודםהבא - סוגי אירועים חדשים ב- Swing 
תגובות הקוראים    תגובות  -  0
דרכונט
מהי מערכת הדרכונט?
אינך מחובר, להתחברות:
דוא"ל
ססמא
נושאי לימוד
חיפוש  |  לא פועל
משלנו  |  לא פועל
גולשים מקוונים: 6