Sei sulla pagina 1di 15

Individual Assignment

CONCURRENT PROGRAMMING

Name : Leong Weng Fon (TP038881)


Intake Code : UC2F1708 (CS)
Module Code : CT074-3-2-CCP
Due Date : 14-MAY-2018
Lecturer : MR.ZAILAN ARABEE BIN ABDUL
SALAM
Word Count : 2109 Words
Table of Contents
1.0 Introduction ............................................................................................................................................ 3
2.0 Discussion of the encapsulation ............................................................................................................. 4
3.0 Code implementation ............................................................................................................................. 5
4.0 UML Class Diagram ............................................................................................................................... 13
5.0 Conclusion ............................................................................................................................................. 14
6.0 Reference ................................................................................................. Error! Bookmark not defined.
1.0 Introduction
The problem of this assignment is An owner of a bus depot suspects that the way in which the
depot is operated means that buses have to spend too much time waiting to be served, and so tend
to go elsewhere instead. In order to evaluate the situation a simulation of the Depot has been
commissioned. This simulation will simply run with text output describing the events as they occur
in the Depot, and collect a minimal amount of statistical data. In this assignment, it required to
create a system about the bus depot management system. It allows the bus to get the service and
clean the bus from this bus depot system. In this assignment requirements, The depot employs two
mechanics and a number of part time cleaners. The depot only have 1 single lane ramp to enter
and exit the facility, which causes some traffic flow issues as the large buses take time to enter and
exit the ramp. The requirement of this assignment is to write a program in which synchronization
and communication takes place between several concurrent processes. It is intended to force you
to solve (and not simply avoid) a range of interesting synchronisation problems.

The flow of the activities in the simulation.The bus depot of the cleaner will not work when raining.
First, the bus need to wait to enter the apprropriate bay. Then, The bus enter the appropriate bay.
Cleaners and mechanics is finding the bus in a queue. Then, the cleaners and mechanics serve the
bus. The bus will go for service either go for clean or mechanics. It depends on the bus. After
served the bus, the bus will wait at the the departures bay and wait to exit the bay.
2.0 Discussion of the encapsulation

Encapsulation is an object-oriented concept where the meaning of it is to hide everything and


not to expose to other classes. This concept is applied in this simulation for the Bus, this
Bus class contains a variable which is private and a public setter and getter (getName
() and setName ()) method. Therefore, any class that wants to access the data have to be
accessed through the setter and getter. In this case, the bus name (id) will be protected and it
will not be repeated or appeared on any other classes.

Figure 1 show the getName() and setName() method. In this assignment, the mechanics,
cleaner and bus will have a name, time. It is to ensure that which bus is going in the bay for
service or/and clean and going out from the bay.
3.0 Code implementation

Thread synchronization

Thread synchronization is the concurrent execution of two or more threads that share critical
resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise,
conflicts may arise when parallel-running threads attempt to modify a common variable at the
same time. To clarify thread synchronization, consider the following example: three threads-
A,B,and C are executed concurrently and need to access a critical resource, Z. To avoid conflicts
when accessing Z, threads A,b and C must be synchronized. Thus, when A accesses Z, and B
also tries to access Z, B’s access of Z must be avoided with security measures until A finishes its
operation and ccome out of Z.

In Java, two synchronization strategies are used to prevent thread interference and memory
consistency errors:

Synchronized method: Includes the synchronized keyword in its declaration. When a thread
invokes a synchronized method, Synchronized method automatically acquires the intrinsic lock
for that method’s object and releases it when the method returns, even if that return was caused
by an uncaught exception.

Synchronized Statement: Declares a block of code to be synchronized. Unlike synchronized


ethods, synchronized statements should specify the objects that provide the intrinsic lock. These
statements are useful for improving concurrency woth fine-grained synchronization, as they
enable the avoidance of unnecessary blocking. (techopedia, 2018)
Figure 2 show the synchronized statement. synchronized statements should specify the objects
that provide the intrinsic lock. It will run the program smoothly and the thread will crush with
each other.

Figure 3 show the synchronized method. Synchronized method automatically acquires the
intrinsic lock for that method’s object and releases it when the method returns, even if that return
was caused by an uncaught exception. It will run the main function of the program smoothly and
ensure that the main function will run based on the thread.
Wait(), notify(), and notifyAll()
Multithreading in java is pretty complex topic and requires a lot of attention while writing
application code dealing with multiple threads accessing one/more shared resources at any given
time. Java 5,introduced some classess like BlockingQueue and Executors which take away some
of the complexity by providing easy to use APIs. Programmers using these classes will feel a lot
more confident than programmers directly handling synchronization stuff using wait() and notify
method calls. I will also recommend to use these newer APIs over synchronization yourself, but
many times we are required to do so far various reasons e.g maintaining legacy code. A good
knowledge around these methods will help you in such situation when arrived. In this tutorial, I
am discussing some concepts around methods wait(), notify() and notifyAll().
Wait()
It tells the calling thread o give up the lock and go to sleep until some other thread enters the
same monitor and calls notify(). The wait() method releases the lock prior to waiting and
reacquires tightly integrated with the synchronization lock, using a feature not available directly
from synchronization mechanism. In other words, it is not possible for us to implement the wait()
method purely in Java: it is a native method.
Notify()
It wakes up one single thread that called wait() in the same object. It should be noted that calling
notify() does not actually give up lock on a resource. It tells a waiting thread that thread wake up.
However, the lock is not actually given up until the notifier’s synchronized bloack has
completed. So, if a notifier calls notify calls notify() on a resource but the notifier still needs to
perform 10 seconds of actions on the resource within its synchronized block, the thread that haad
been waiting will need to wait at least another additional 10 seconds for the notifier to release the
lock on the object, even through notify() had been called.
notifyAll()
it wakes up all the threads that called wait() on the same object. The highest priority thread will
run first in most of the situation, through not guaranteed. Other things are same as notify()
method above. (Gupta, 2015)
Figure 4 show the notify(). It tells a waiting thread that thread wake up. However, the lock is not
actually given up until the notifier’s synchronized bloack has completed. If the listCleaner size
==1, and it will wake up.

Figure 5 show the wait(). The wait() method releases the lock prior to waiting and reacquires
tightly integrated with the synchronization lock, using a feature not available directly from
synchronization mechanism. While the listCleaners size ==0, the listCleaners will wait.
Sleep() and wait()
Sleep() is a method which is used to hold the process for few seconds or time you wanted but in
case of wait() method thread goes in waiting state and it won’t come automatically until we call
notify() or notifyAll().
Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time.
The thread keeps the monitors it has acquired – i.e. if the thread is currently in a synchronized
block or method no other thread can enter this block or method. If another thread calls
thread.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which
means that it always affect the current thread (the one that is executing the sleep method). A
common mistake is to call thread.sleep() where is a different thread; even then,it is the current
thread that will sleep, not the t thread.
Object.wait() sends the currrent thread into the “Not Runnable” state, like sleep(), but with a
twist. Wait is called on an object, not a thread; we call this object the “lock object”. Before
lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases
this lock, and adds the hread to the “wait list” associated with the lock. Later, another thread can
synchronize on the same lock object and call lock.notify(). This wakes up the originak, waiting
thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not needa
direct pointer to sleeping thread, but only to the shared lock object. (Safaribooksonline, 2018)

Figure 6 show the sleep(). In this assignment, implement code sleep() is to hold the process for
few seconds or time you wanted but in case of wait() method thread goes in waiting state and it
won’t come automatically until we call notify() or notifyAll(). It will see output clearly and the
output will display in order.
Runnable

In java language, as we all know that there are two ways to create threads. One using Runnable
interface and another by extending Thread class. Implementing Runnable is the preferred way to
do it. Here, you’re not really specializing or modifying the thread’s behaviour. You’re giving the
thread something to run. That means composition is the better way to go. Implementing
Runnable makes your class more flexible. If you extend thread then the action you’re doing
always going to be in a thread. However, if you extend Runnable it doesn’t have to be. You can
run it in a thread, or pass it to some kind or executor service, or just pass it around as a task
within a single threaded application. (Gupta, 2013)

Figure 7 show the runnable. Put runnable in the class object, it will make your class more
flexible.
Generate Random Number
If two instances of Random are created with the same seed, and the same sequence of method
calls is made for each, they will generate and return identical sequences of numbers. In order to
guarantee this property, particular algorithms are specified for the class Random. Java
implementations must use all the algorithms shown here for the class Random, for the sake of
absolute portability of Java code. However, subclasses of class Random are permitted to use
otherr algorithms, so long as they adhere to the general contacts for all the methods.
The algorithms implemented by class Random use a protected utility mehod that on each
invocation can supply up to 32 pseudorandomly generated bits.
Many applications will find the method Math.random() simpler to use.
Instances of java.util.Random are threadsafe. However, the concurrent use of the same
java.util.Random instance across threads may encounter contention and consequent poor
performance. Consider instead suing ThreadLocatRandom in multithreaded designs.
Instances of java.util.Random are not cryptograhically secure. Consider instead using
SecureRandom to get a cryptograhically secure pseudo-random number generator for use by
security-sensitive applications. (ClassRandom, 2018)
Figure 8 show generate random number. First need to range the number between maximum and
minimum number and return the number to generate number. It will repeat the numbers once
again.
4.0 UML Class Diagram
5.0 Conclusion

As a conclusion, the assignment has been done completed on time. Before I study this module,
have learned some java languages in my diploma program. So, I have some basic java
programming languages then easier for me to do this assignment, but I also meet some problem
when doing the assignment. During the process of doing assignment, there are some problems
that have face such as bugs and errors. However, these problems have been solved immediately
because of get help from friends and lecturer to solve the problem. In this assignment, I have
learned more java programming languages before I have learned java programming in my
diploma program. Although try to get output or result, but hard to get the output or result. In the
future, hope that will more improve the programming language exp. Java,C++,C# and so on.
6.0 References
ClassRandom, 2018. [Dalam talian]
Available at: https://docs.oracle.com/javase/7/docs/api/java/util/Random.html
[Diakses 2018].

Gupta, L., 2013. HowToDoInJava. [Dalam talian]


Available at: https://howtodoinjava.com/core-java/multi-threading/difference-between-implements-
runnable-and-extends-thread-in-java/
[Diakses 12 3 2013].

Gupta, L., 2015. HowTO DoInJava. [Dalam talian]


Available at: https://howtodoinjava.com/core-java/multi-threading/how-to-work-with-wait-notify-and-
notifyall-in-java/
[Diakses 8 1 2015].

Safaribooksonline, 2018. [Dalam talian]


Available at: https://www.safaribooksonline.com/library/view/java-threads-
second/1565924185/ch04s04.html
[Diakses 2018].

techopedia, 2018. [Dalam talian]


Available at: https://www.techopedia.com/definition/24349/thread-synchronization
[Diakses 2018].

Potrebbero piacerti anche