Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Create a program that runs two threads which write two different messages a specified number of times to the same text file in append mode.

Create a program that runs two threads which write two different messages a specified number of times to the same text file in append mode. For example, the thread 1 may write "hi" 10 times to a text file and the thread 2 may write "bye" 10 times to the same file in append mode. Each time, a thread writes the message to the file, it sleeps 100 milliseconds to simulate the end of its time slice. 

 

Without synchronization, the expected output to the file is a random mixture of "hi" and "bye" messages depending upon the sequence in which the two threads are scheduled to run by the scheduler (a part of the operating system). Synchronize the code such that the two threads take turn writing to the file. Accomplish this by using Java's cooperative synchronization mechanism which provides for notify and wait.

Co-operative Synchronization

Java provides for co-operative synchronization in which multiple threads coâ??operatively synchronize their executions in accomplishing a task. When one thread is done with its part of the task, it notifies the other threads of that using Java provided notify method and put itself in a wait state using Java provided wait method.

Consider, a reader/writer problem in which one thread writes to a buffer and another thread reads from that buffer and they take turns doing that. In that case, when the writer thread finishes writing, it calls the notify method to awaken the reader thread and calls the wait method to put itself in the wait state. Then, the reader thread runs and reads from the buffer. After it is done, it calls the notify method to awaken the writer thread and calls the wait method to put itself in wait state. Then the whole process repeats. In this fashion, the two threads cooperatively synchronize using notify and wait.

In Java, the Object class provides the wait and notify methods. Since, in Java, the Object class is the top class, all other classes inherit its notify and wait methods. The threads which want to synchronize cooperatively on a task, they call the notify and the wait methods of the same object as described above.

Also, to ensure that the notify and the wait methods executing on one thread are not interrupted by notify and wait methods executing on another thread, Java requires that notify and wait method calls be put in a competitive synchronized block.

Implementation

class CoopSyncRunnable

Create a class CoopSyncRunnable that implements Runnable and provides the following:

·It provides a String variable message that specifies the message to be written to the file, an int variable count that specifies the number of times the message is written, a String variable fileName that specifies the file name where the message is written and an object of class Object that is used for synchronizing threads.

·It provides a constructor for initializing the above variables.

·It provides a run method that implements the Runnable interface. The run method which provides a loop that writes the above message count number of times to the file. After writing each time, it issues a notify to awaken the other thread and then calls wait to put itself in wait state as shown in the run method below.

Sample code

public void run() {

try {

PrintWriter pw = new PrintWriter

(new FileWriter (fileName,true), true);

Thread.sleep (100); //simulated time slice

for (int i=0; i

synchronized (obj) {

//A single write within the loop will be here

pw.println (message);

Thread.sleep (100); //simulated time slice

obj.notify ( );

obj.wait ( );

}

Thread.sleep (100);

}

synchronized (obj) {

obj.notify ();

}

}

catch (Exception ex){

ex.printStackTrace();

}

}

Class TestCoopSyncRunnable

Create a class TestCoopSyncRunnable containg the main method which provides the following:

·It creates an object of class Object as shown below. This object will be used both competitive and cooperative for synchronization.

Object syncObj = new Object ();

·It inputs two messages: one to be written to the file by the first Thread and the second for writing to the file by the second thread. It also inputs the total number of the times both messages is written and the name of the file where messages are written.

·It creates an instance of CoopSyncRunnable and pass its constructor the message1, count, fileName, and object.

·It creates a second instance of CoopSyncRunnable and pass its constructor message2, count, fileName, and object.

·It creates the first Thread object and passes it the first CoopSyncRunnable.

·It creates the second Thread object and passes it the second CoopSyncRunnable.

·It calls the start method of both the Thread objects.

Sample Code

Object syncObj =new Object();

CoopSyncRunnable coopSync1 =

new CoopSyncRunnable("hi",10,"CoopSync.txt", syncObj);

CoopSyncRunnable coopSync2 =

new CoopSyncRunnable("bye",10," CoopSync.txt ", syncObj);

Thread t1 = new Thread(coopSync1);

Thread t2 = new Thread(coopSync2);

t1.start();

t2.start();

Testing

Input

Run the program for the following input

Message 1: hi

Message 2: bye

Message count: 10

Output file name: CoopSync.txt

Output

Either hi and bye written alternately to the file

or bye and hi written alternately to the file

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

hi

bye

Turn In

The contents of source files.

The contents of the output file.

Step by Step Solution

3.43 Rating (156 Votes )

There are 3 Steps involved in it

Step: 1

The Implementations of the provided of the provided recruitments in java import javaioFileWriter imp... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction to Java Programming, Comprehensive Version

Authors: Y. Daniel Liang

10th Edition

133761312, 978-0133761313

More Books

Students also viewed these Operating System questions

Question

What are the two most abundant igneous rocks?

Answered: 1 week ago