• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads and Synchronization examples

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
where did i get practical code snippets for threads and synchronization
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here: http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
 
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you could create this code

1. open notepad
2. start code
3. compile
4. test

 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here are the questions and Answers

********************************************

Sample test

1. Which of the following are valid ways of creating and starting a thread?








2. Consider the following code.







Which of the following can print the message “Just checking…” after execution?









3. Consider the following code that creates a thread object using a runnable object.







Which of the following can be the valid definitions for class MyRunnable for the preceding code to compile successfully?



A. public class MyRunnable extends Runnable { public void run() {} }

B. public class MyRunnable implements Runnable { public int run(){} }

C. public class MyRunnable implements Runnable { protected void run(){} }

D. public class MyRunnable extends Thread implements Runnable { public void start(){} }

E. public class MyRunnable implements Runnable { public void run(){} }

F. public class MyRunnable implements Runnable { public void run();}





4. Consider the following code.






What is the result of executing the Java application MyThread?



A. “Running 1...” is printed five times followed by “Running 2...” five times.

B. “Running 1...” is printed five times.

C. This code will fail to compile at line 10.

D. This code will fail to compile at line 18.

E. The output will have “Running 1...” five times and “Running 2...” five times. However, there order cannot be predicted.

F. This class will compile but will fail to run because the thread is not started before invoking run().





5. Which of the following statements true about the given code? (Choose all the correct answers)






A. When this Java application runs, only the thread job1 will ever get a chance to execute. job2 and job3 will never get a chance to execute.

B. This code will not compile as the setPriority() can be called on only the currently executing thread.

C. When this Java application runs, job2 or job3 may get a chance to execute if they are started before the thread job1.

D. Each of these three threads will take time slots for execution and will give up their turn of execution after a specified time. Since job1 has highest priority, it gets to run longest.

E. How the three threads will execute cannot be said with a guarantee. It depends on the implementation of thread scheduler and JVM.





6. Consider the following classes.








Which of the following statements are true when application Jetliner is executed?



A. The message “going really fast” may not be immediately followed by “done” in the output due to the call at line 16.

B. The call at line 16 makes sure that the message “going really fast” will be always immediately followed by “done” in the output.

C. This code will not compile as you cannot call bullockCartThread.yield() in jetlinerThread’s run method.

D. Once bullockCartThread starts executing, it will give up its turn only after printing the message “going really slow” 50 times.

E. Since jetlinerThread is started first, it is guaranteed to finish before the bullockCartThread.





7. Consider the following class.



1. public class Garfield implements Runnable {

2. public void run() {

3. try {

4. Thread.sleep(3000);

5. } catch (InterruptedException e) {}

6. System.out.println("Good morning everyone!");

7. }

8.

9. public static void main(String[] args) {

10. Garfield g = new Garfield();

11. new Thread(g).start();

12. }

13. }





Assuming the thread is never interrupted, which of the following statements are true about the Garfield class?



A. This application will fail to compile at line 10.

B. Whenever new thread started on g executes, its execution will stop at line 4 for at most 3 seconds and then message “Good morning everyone!” is printed.

C. Whenever new thread started on g executes, its execution will stop at line 4 and exactly after 3 seconds the message “Good morning everyone!” is printed.

D. Whenever new thread started on g executes, its execution will stop at line 4 for at least 3 seconds. Sometime after that the message “Good morning everyone!” is printed.

E. The message “Good morning everyone!” is never printed because the new thread started on g will not wake up unless it is interrupted.





8. A Java program creates three threads t1, t2 and t3. They all work on a common object someObject. After sometime during their execution, they all are waiting for notification in someObject’s waiting pool. However, someObject wants to notify only t1 and t3 but not t2. How it can be done?



14. t1.notify(); t3.notify();

15. t1.notify(); t3.notify(); t2.wait();

16. someObject.notify(t1); someObject.notify(t3);

17. someObject.notifyAll();

18. someObject.notifyAll(t1,t3);

19. It is impossible to do so.





9. Consider the following MainThread class.



1. package com.example.threads;

2. public class MainThread extends Thread {

3. private int i;

4. public static void main(String [] args) {

5. MainThread t1 = new MainThread();

6. MainThread t2 = new MainThread();

7. t1.printIt();

8. t2.printIt();

9. t1.start();

10. t2.start();

11. }

12. public void run() {

13. System.out.print(i++ + " ");

14. }

15. public void printIt() {

16. System.out.print(i++ + " ");

17. }

18. }



What will be printed when MainThread is executed?



A. 0 1 2 3

B. 1 0 3 2

C. 0 0 1 1

D. 0 1 0 1

E. The output cannot be predicted.





10. Which of the following calls on object myObj invoke the methods of Object class?



A. myObj.notify();

B. myObj.synchronized();

C. myObj.yield();

D. myObj.wait(1000);

E. myObj.wait(1000,0);

F. myObj.sleep(1000);

G. myObj.notifyAll();





11. Which of the following methods can be invoked on the object of type Thread?

A. running()

B. start()

C. wait()

D. wakeup()

E. notify()

F. run()

G. waiting()





12. Which of the following statements are true about synchronization?



A. A Java object has multiple locks. Each thread executing a synchronized code on an object acquires one from the object.

B. When a thread invokes wait() on object, it immediately releases that object’s lock.

C. If a class has synchronized methods, multiple threads must first acquire a lock on its object before invoking any methods of that class.

D. You must protect the common variables from concurrent access by declaring them using the synchronized keyword.

E. When a thread yields, it automatically goes to sleep until a high priority threads are present in thread pool.





13. Which of the following statements are true about the wait and notify mechanism and methods?



A. The thread waiting for notification holds the lock all the time it is waiting.

B. The thread sleeping for some predefined time holds the lock all the time it is sleeping.

C. To call wait(), an object must own the lock of the thread that is going to wait.

D. The notifyAll() is a static method of Object class.

E. The notify() method causes a thread to immediately release its locks.

F. You need to call the notify() method in synchronized block but not the notifyAll() method.

G. The method notifyAll()notifies all waiting threads regardless of the object they’re waiting on.





14. If a thread t1 calls wait() on an object myObject as myObject.wait(10000); in a properly synchronized code. What will happen to the thread t1 after this call?



A. t1 will start executing as soon as it is notified or exactly after ten seconds.

B. t1 will immediately start executing if the lock on myObject is released within ten seconds.

C. t1 comes out of waiting state and enters the ready-to-run state when either it is notified or when the ten seconds are elapsed since it started waiting.

D. t1 keep waiting until someone calls myObject.notifyAll().

E. Ten seconds after t1 started waiting, it notifies all the waiting threads on someObject.





15. Imagine that we have a GUI application program for editing image files. This application has two threads, one thread ( called the paintThread) is responsible for painting the images and the other (processInputsThread) for handling the user inputs. The paintThread takes a lot of time to paint the image and is extremely slow. On the other hand, the processInputsThread quickly process the user inputs. If the JVM we are using respects thread priorities while thread scheduling, what would be the better way of setting priorities of these threads to make the GUI application responsive to the user inputs even while painting a large image?



A. paintThread.setPriority(Thread.NORM_PRIORITY);

B. paintThread.setPriority(1);

C. paintThread.setPriority(10);

D. paintThread.setPriority(0);

E. paintThread.setPriority(Thread.MIN_PRIORITY);

F. paintThread.setPriority(5);



Answers
********************************************************

Answers with explanations

1. þ C

The correct answer is C. Note that Runnable is an interface. This option implements this interface with anonymous inner class and then correctly starts the thread.

Options A,B D are incorrect as they try to instantiate an interface Runnable which is invalid. E is incorrect as it creates thread object correctly but does not start it.



2. þ A C D E

The correct answers are A C D and E. All these options invoke the run() method by one way or the other. C and E directly invoke this method. Option A creates and starts a thread that will eventually invoke it. D creates a thread, but does not start it. Instead it invokes the run() method as a normal method.

Options B is incorrect. B will not even compile as class MyRunnable does not have any start() method.



3. þ E

The correct answer is E. The Runnable interface has a single method public void run() and option E correctly implements it.

A is incorrect; you can never extend an interface, you always implement it. B and C are incorrect, as the MyRunnable is not implementing the run method correctly. The run method in B has incorrect return type and C is reducing the visibility of run() method by applying a more restrictive modifier (public -->protected) which is not allowed. D is incorrect as it is not implementing the run() method. F is incorrect as it is defining run() without a method body.



4. þ B

The correct answer is B. The run() method on thread object t1 will be invoked like any ordinary Java method.

A is incorrect as run() method that takes int argument is never called. C is incorrect; the run(int) method is correctly overloading the run() method and hence there won’t be any compilation problem. D is incorrect as there is nothing wrong in invoking run method like this. E is incorrect for two reasons; there is no question of having “Running 2...” in output as run(int) is never called. The output is very much predictable, as this class is not creating any new thread-of-execution. Hence, everything will be executed in a single thread sequentially. F is also incorrect, you can invoke run() method on a thread object.



5. þ E

The correct answer is E. How this code will run depends on the scheduler’s implementation – which algorithms it use, is it priority-based or time-sliced or combination of multiple algorithms etc.

A could be true in purely priority-based scheduler. B is incorrect, you can set priority before starting a thread. C and D are also possible but you can never be sure. Therefore, the bottom line is you cannot guarantee how this code will work across different implementations of Java.



6. þ A

The correct answer is A. The exact output of this code depends on the scheduler’s implementation and may not be same each time you execute it. The call at line 16 could be misleading. But remember that bullockCartThread.yield(); in a jetlinerThread’s run code will cause jetlinerThread to give up its turn of execution. yield() is a static method that causes the current thread to yield. Since the call bullockCartThread.yield(); is in jetlinerThread’s run code, the thread jetlinerThread will be the current thread at that time and it will yield. Since the option A is suggesting a possibility (and not guarantee) it is a true option.

Options B D E are all incorrect as they talk about a guaranteed behavior which is not true. C is incorrect; since yield is a static method, it can be called on any of the thread instances.



7. þ D

The correct answer is D. The call sleep(3000) causes the new thread started on g to sleep for 3 seconds. After it wakes up it goes to ready-to-run state. Only after it is again scheduled to run it can print the message “Good morning everyone!”. So all we can say is that this message will be printed sometime after three seconds have elapsed.

A is incorrect; it is a valid way in which the thread is created and started in the same step. B is incorrect, as the new thread (started on g) will definitely sleep for 3 seconds (if it is not interrupted). The word atmost suggest that the thread can wake up before three seconds are elapsed which is not correct. C is incorrect as there is no guarantee that the thread will start executing immediately after it wakes up. E is incorrect as the thread automatically goes from sleeping to ready-to-run state after the sleep time is elapsed. You need not do anything to wake it up.



8. þ F

The correct answer is F. You do not have any control as to which thread gets notified. Therefore, you cannot specifically notify only two of the three waiting threads.

A and B are incorrect for the same reason. Note that they are calling notify() on thread objects which is not correct as the question clearly says that the threads are waiting on someObject, therefore the notify() should be called on someObject to notify the threads waiting on it. C and E are incorrect use of notify methods. D is syntactically correct but it will notify all the three threads t1, t2 and t3.



9. þ C

The correct answer is C. The call to printIt() at line 7 and 8 are invoked before the threads are started. Therefore, there is no uncertainty yet. Since both threads are different Java objects, each has its own instance variable i which will be 0 initially. Thus 0 0 will be printed. Now t1.i will be 1 and t2.i will also be 1. Remember that they are two different objects. Now when the threads are started at line 9 and 10, we do not know which one will get its turn first. But since they are different objects, they are operating on two separate copies of i. If t1 gets to execute first, it will print t1.i and increment it (t1.i ). Therefore, it will print 1 and increment i so that t1.i will be 2. Similarly when t2 is executed it will print t2.i which is 1 and increment t2.i . Interesting the order in which t1 or t2 will be executed (t1 first or t2 ?) will not change the output in this case.



10. þ A D E G

The correct answers are A D E and G. A calls the notify() method of Object class. G calls the notifyAll() method of Object class. D and E are calls to the overloaded wait() methods of Object class that allows the threads to wait for some predefined time. The first argument in both wait calls is the timeout in milliseconds. The second argument in option E is the additional timeout in nanoseconds.

B C and F are all incorrect options. B is incorrect, as there is no method called synchronized in any of the threading related classes let alone Object class. C and F are calls to the Thread class’s method.





11. þ B C E F

The correct answers are B C E and F. B represents the start() method invokes when you wish to start the thread. F represents the run() method usually invoked internally (by JVM) sometime after start() is called. C and E are the methods of Object class. Since Thread class (like all other Java classes) inherits from the Object class, you can call these inherited methods on an object of type Thread.

A D and G are all incorrect options. There are no such methods in Thread class.



12. þ B

The correct answer is B. A thread immediately releases an object’s lock after it invokes the wait() method on it to give the other threads a chance to get that object’s lock.

A C D and E are all incorrect statement. A is incorrect; A Java object has a single lock which can be awarded to only one thread at a time. C is incorrect, as threads do not need lock for accessing the non-synchronized methods of Java object. D is incorrect as you can synchronize only methods or code blocks. E is incorrect as a call to yield() takes the thread back to ready-to-run state (and not to the sleeping state).



13. þ B

The correct answer is B. The thread that has acquired an object’s lock keeps it even while sleeping.

A C D E F and G are all incorrect statements. A is incorrect; thread immediately release the lock after a call to a wait(). It does not try to acquire lock while it is waiting for notification. C is incorrect, as the thread calls an object’s wait() method and hence it is the one that needs to acquire the lock (not the other way). D is incorrect; notifyAll() is an instance method of Object class. E is incorrect; a call to notify() do not immediately release the lock. The thread calling it will keep the lock as long as it is in the synchronized block in which notify() is called. G is incorrect as notifyAll() (on an object) notifies only to the threads waiting on that object.



14. þ C

The correct answer is C. The call wait(10000) sets a timeout for waiting. The thread t1 will wait for maximum 10 seconds for notification. If it receives it before 10 seconds, fine. Otherwise, it anyway stops waiting.

A B D and E are all incorrect. A is incorrect, as t1 do not start executing right away after the wait is over. It has to contend again with the other threads to get a turn-to execute. B is incorrect as t1 is waiting on notification and not on lock. D is incorrect as wait(10000) causes a timed waiting. Therefore, it does not keep waiting. E is incorrect as t1 is the one waiting, so it does not notify.



15. þ B E

The correct answer is D. Thread.MIN_PRIORITY is the lowest priority (1) that a thread can have. Since paintThread is slow, it should have a low priority so that it cannot stop other threads from executing.

A C D and F are all incorrect. Please note that 1 is considered as lowest priority and 10 is considered as highest priority. C is incorrect as with priority 10, the painterThread will grab the JVM and will never give it to any other threads with lesser priority. Moreover, it’s a slow thread so it will take lot of time before other thread processInputsThread will get a chance to execute, making the GUI application poorly responsive. A and F will keep a normal priority to thread which is not good to give a higher preference to processInputsThread over paintThread. D is incorrect, as thread priority must be between 1 to 10.
 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Prav, Quote the Source.
 
Ranch Hand
Posts: 182
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
very helpful questions....

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Banu Chowdary wrote:What does it mean???

When using HashSet or LinkedHashSet, the objects you add to them
must override hashCode(). If they don’t override hashCode(), the default Object.
hashCode() method will allow multiple objects that you might consider "meaningfully
equal" to be added to your "no duplicates allowed" set. (K&S)



Well, a set is only supposed to contain UNIQUE elements. So, the problem comes to what is the definition of unique. For many of us (and probably the get() methods implementations of the List interface), as long as equals(Object o) method returns true, we will consider two objects to be the same. But for HashSet and LinkedHashSet, two conditions has to be met: 1) equals method returns true, and 2) the return value of hashCode for two objects has to be the same value. Therefore, if one wants to use HashSet and LinkedHashSet in a "meaningful" way, one has to override both equals and hashCode methods.
 
Prav sharma
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Abhi vijay wrote:Prav, Quote the Source.



Hi Abhi

Its a legal source
Here is the link

http://www.witscale.com/ebook/Browsable/ebook118.htm
 
kar vasireddy
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Prav..
very useful questions
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic