Sie sind auf Seite 1von 9

Program based on Multithreading

Q.1 Declare a class ThreadExample which has counter class, as a nested class in your program:

static class Counter {


int count;
void inc() {
count = count+1;
}
int getCount() {
return count;
}
}

Create several threads, start them all, and wait for all the threads to terminate. Each thread
increments the counter a specified number of times. After all the threads have completed, the
value of the counter is printed out so it can be compared to the correct value. The user specifies
the number of threads and the number of times each thread increments the counter. Print the
final value of the counter, and see whether it is correct.

class Threadexample{
static class Counter {
int count;
void inc() {
count = count+1;
}
int getCount() {
return count;
}
}

static Counter counter; // The counter that will be incremented.


static int numberOfIncrements; // Number of times each thread will increment it.

static class IncrementerThread extends Thread {


public void run() {
for (int i = 0; i < numberOfIncrements; i++) {
counter.inc();
}
}
}
public static void main(String[] args) {

Scanner in = new Scanner(System.in); // For reading the user's


inputs.

while (true) {
/* Get number of threads and number of increments per thread
* from the user. Exit if number of threads is <= 0. */

System.out.println();
System.out.print("How many threads do you want to run (Enter 0 to
end)? ");
int numberOfThreads = in.nextInt();
if (numberOfThreads <= 0)
break;

do {
System.out.println();
System.out.println("How many times should each thread
increment the counter? ");
numberOfIncrements = in.nextInt();
if (numberOfIncrements < 1) {
System.out.println("Number of increments must be
positive.");
numberOfIncrements = 1;
}
} while (numberOfIncrements <= 0);

System.out.println();
System.out.println("Using " + numberOfThreads + " threads.");
System.out.println("Each thread increments the counter "
+ numberOfIncrements + "
times.");

/* Create the threads and start them. */

System.out.println();
System.out.println("Working...");
System.out.println();
IncrementerThread[] workers = new
IncrementerThread[numberOfThreads];
counter = new Counter();
for (int i = 0; i < numberOfThreads; i++)
workers[i] = new IncrementerThread();
for (int i = 0; i < numberOfThreads; i++)
workers[i].start();

/* Wait for all threads to terminate. */

for (int i = 0; i < numberOfThreads; i++) {


try {
workers[i].join();
}
catch (InterruptedException e) {
}
}

/* Display the results. */

System.out.println("The final value of the counter should be "


+
(numberOfIncrements*numberOfThreads));
System.out.println("Actual final value of counter is: " +
counter.getCount());
System.out.println();
System.out.println();

} // end while

} // end main()

} // end class UnsynchronizedCounterTest


OUTPUT
How many threads do you want to run (Enter 0 to end)? 3
How many times should each thread increment the counter? 3
Using 3 threads.
Each thread increments the counter 3 times.
Working...
The final value of the counter should be 9
Actual final value of counter is: 9

Q. 2 Which integer between 1 and 10000 has the largest number of divisors, and how many
divisors does it have? Write a program to find the answers and print out the results. It is possible
that several integers in this range have the same, maximum number of divisors. Your program
only has to print out one of them. The basic idea is to go through all the integers, keeping track
of the largest number of divisors in the given range. Also, keep track of the integer that had that
number of divisors. Make use of multiple threads and wait till threads die to get result. Use the
following pseudocode

for each integer N from 1 to 10000:


Count the number of divisors of N
If that number is greater than maxDivisors:
Let maxDivisors = the number of divisors of N
Let numWithMax = N
Output maxDivisors and numWithMax

/*** This program finds the number in the range 1 to some maximum that has the
largest number of divisors. It prints that number and the number of divisors
that it has. */

public class CountDivisorsUsingThreads {

private final static int MAX = 100000;

private volatile static int maxDivisorCount = 0;

private volatile static int intWithMaxDivisorCount;

synchronized private static void report(int maxCountFromThread,


int intWithMaxFromThread) {
if (maxCountFromThread > maxDivisorCount) {
maxDivisorCount = maxCountFromThread;
intWithMaxDivisorCount = intWithMaxFromThread;
}
}

private static class CountDivisorsThread extends Thread {


int min, max;
public CountDivisorsThread(int min, int max) {
this.min = min;
this.max = max;
}
public void run() {
// System.out.println("Thread " + this + " testing range " +
// min + " to " + max); // For testing.
// long startTime = System.currentTimeMillis();
int maxDivisors = 0;
int whichInt = 0;
for (int i = min; i < max; i++) {
int divisors = countDivisors(i);
if (divisors > maxDivisors) {
maxDivisors = divisors;
whichInt = i;
}
}
// long elapsedTime = System.currentTimeMillis() - startTime;
// System.out.println("Thread " + this + " used " +
// (elapsedTime/1000.0) + " seconds."); // for testing.
report(maxDivisors,whichInt);
}
}

private static void countDivisorsWithThreads(int numberOfThreads) {


System.out.println("\nCounting divisors using " +
numberOfThreads + " threads...");
long startTime = System.currentTimeMillis();
CountDivisorsThread[] worker = new CountDivisorsThread[numberOfThreads];
int integersPerThread = MAX/numberOfThreads;
int start = 1; // Starting point of the range of ints for first thread.
int end = start + integersPerThread - 1; // End point of the range of
ints.
for (int i = 0; i < numberOfThreads; i++) {
if (i == numberOfThreads - 1) {
end = MAX; // Make sure that the last thread's range goes all
// the way up to MAX. Because of rounding, this
// is not automatic.
}
worker[i] = new CountDivisorsThread( start, end );
start = end+1; // Determine the range of ints for the NEXT thread.
end = start + integersPerThread - 1;
}
maxDivisorCount = 0;
for (int i = 0; i < numberOfThreads; i++)
worker[i].start();
for (int i = 0; i < numberOfThreads; i++) {
// Wait for each worker thread to die, because the results
// are not complete until all threads have completed and
// reported their results.
while (worker[i].isAlive()) {
try {
worker[i].join();
}
catch (InterruptedException e) {
}
}
}
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("\nThe largest number of divisors " +
"for numbers between 1 and " + MAX + " is " + maxDivisorCount);
System.out.println("An integer with that many divisors is " +
intWithMaxDivisorCount);
System.out.println("Total elapsed time: " +
(elapsedTime/1000.0) + " seconds.\n");
}

public static void main(String[] args) {


int numberOfThreads = 0;
while (numberOfThreads < 1 || numberOfThreads > 10) {
System.out.print("How many threads do you want to use (1 to 10) ?
");
numberOfThreads = TextIO.getlnInt();
if (numberOfThreads < 1 || numberOfThreads > 10)
System.out.println("Please enter a number from 1 to 10 !");
}
countDivisorsWithThreads(numberOfThreads);
}

public static int countDivisors(int N) {


int count = 0;
for (int i = 1; i <= N ; i++) {
if ( N % i == 0 )
count ++;
}
return count;
}

Q.3 Create a class called MyCurrentDate that implements Runnable interface. The MyCurrentDate
class displays the current date and time 10 times, with 100 milliseconds interval - use
sleep() m ethod for this interval.Create a class called MyMain , which contains main() method, in
which 3 instances of MyCurrentDate threads are being run.

Q. 4 In producer–consumer problem (also known as the bounded-buffer problem) has two


processes, the producer and the consumer, which share a common, fixed-size buffer used as a
queue.

 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
Write a multi-process synchronization program to make sure that the producer won’t try to add
data into the buffer if it’s full and that the consumer won’t try to remove data from an empty
buffer. Use following classes in program

Q : the queue that you’re trying to synchronize

Producer : the threaded object that is producing queue entries

Consumer : the threaded object that is consuming queue entries

PC : the driver class that creates the single Q, Producer, and Consumer.

import java.util.concurrent.Semaphore;

class Q
{
// an item
int item;

// semCon initialized with 0 permits


// to ensure put() executes first
static Semaphore semCon = new Semaphore(0);

static Semaphore semProd = new Semaphore(1);

// to get an item from buffer


void get()
{
try {
// Before consumer can consume an item,
// it must acquire a permit from semCon
semCon.acquire();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}

// consumer consuming an item


System.out.println("Consumer consumed item : " + item);

// After consumer consumes the item,


// it releases semProd to notify producer
semProd.release();
}

// to put an item in buffer


void put(int item)
{
try {
// Before producer can produce an item,
// it must acquire a permit from semProd
semProd.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}

// producer producing an item


this.item = item;

System.out.println("Producer produced item : " + item);

// After producer produces the item,


// it releases semCon to notify consumer
semCon.release();
}
}

// Producer class
class Producer implements Runnable
{
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


for(int i=0; i < 5; i++)
// producer put items
q.put(i);
}
}

// Consumer class
class Consumer implements Runnable
{
Q q;
Consumer(Q q){
this.q = q;
new Thread(this, "Consumer").start();
}

public void run()


{
for(int i=0; i < 5; i++)
// consumer get items
q.get();
}
}

// Driver class
class PC
{
public static void main(String args[])
{
// creating buffer queue
Q q = new Q();
// starting consumer thread
new Consumer(q);

// starting producer thread


new Producer(q);
}
}

Q.5 Write a program that has following classes:class Even extends Thread that prints first five even
integers (i.e. 2 4 6 8 10).After printing there should be sleep interval of 1000 msec. class Odd
extends Thread that prints first five odd integers (i.e. 1 3 5 7 9).After printing there should be
sleep interval of 1000 msec. public class TestEvenOdd: In this class creates objects of class Even
and class Odd and invoke threads

Q. 6 Let's say there is only 1 ticket available in train, and two passengers are trying to book that ticket at
same time without synchronization. It might happen that both might end up booking up ticket, though only
ticket was available, which is of course going to create problem.But if synchronization was there only of
them would have been able to book ticket.
class TicketBooking implements Runnable{
int ticketsAvailable=1;

public void run(){

System.out.println("Waiting to book ticket for : "+Thread.currentThread().getName());


if(ticketsAvailable>0){
System.out.println("Booking ticket for : "+Thread.currentThread().getName());

//Let's say system takes some time in booking ticket (here we have taken 1 second time)
try{
Thread.sleep(1000);
}catch(Exception e){}

ticketsAvailable--;
System.out.println("Ticket BOOKED for : "+ Thread.currentThread().getName());
System.out.println("currently ticketsAvailable = "+ticketsAvailable);
}
else{
System.out.println("Ticket NOT BOOKED for : "+ Thread.currentThread().getName());
}

}
public class MyClass {
public static void main(String args[])
{
TicketBooking obj=new TicketBooking();

Thread thread1=new Thread(obj,"Passenger1 Thread");


Thread thread2=new Thread(obj,"Passenger2 Thread");

thread1.start();
thread2.start();

}
}
OUTPUT
Waiting to book ticket for : Passenger1 Thread
Waiting to book ticket for : Passenger2 Thread
Booking ticket for : Passenger1 Thread
Booking ticket for : Passenger2 Thread
Ticket BOOKED for : Passenger1 Thread
currently ticketsAvailable = 0
Ticket BOOKED for : Passenger2 Thread
currently ticketsAvailable = -1

Das könnte Ihnen auch gefallen