Lesson 10

Multi thread programming.

Objectives

Understanding Java Threads:

  • Creating threads using Thread class and Runnable interface;
  • Starting threads;
  • Multual exclusion using synchronized keyword;
  • Putting on wait and resuming threads using wait() and notify()

Documentation

Exercises

Exercise 1

Test 'Counter' programm from section Fire de executie. Replace start() method with run() method and observe the new behavior of the application.

Exercise 2

Test 'TestSincronizare' programm from section Fire de executie. Uncomment synchronized blocks in FirGet and FirSet classes and test again the program. Compare the 2 different behaviors of the application - when using synchronized blocks and not using synchronized blocks.

Exercise 3

Create 2 counters implemented using threads. First counter is incremented from 0 to 100. Second counter is incremented from 100 to 200 and start only after the first counter finish it's job.

Exercise 4

Create a Robot class which simulate a robot which moves randomly in a 2D space (with a limited dimension of 100×100). Add in the 2D space 10 robots and start them. If at a particular point 2 robots arrives on the same location will collide and both of them are destroyed. The robots change their position at each 100 milliseconds.

Exercise 5

Test consumer-producer application from section Fire de executie.

Exercise 6

Create a chronometer in Java (including an UI). The chronometer will have 2 buttons. First button will start and pause the chronometer. Second button will reset the chronometer. The chronometer will be implemented as a java thread. wait/notify/synchrnozed must be used for implementing the chronometer behavior.