Sie sind auf Seite 1von 15

Modern Programming Tools

& Techniques I for Honors


HomeWork 3:-

Rohan Pahwa
Roll No-A17
REG No-10809673
MCA(hons).
Course Code: CAP360 Course Title:Modern Programming Tools & Techniques-III

Homework 3

PART A
1. What java interface must be implements by all threads?
Ans :- Interfaces provide a way for programmers to lay the repository of
a class. They are used to design the requirements for a set of classes to
implement. The interface sets everything up, and the class or classes
that implement the interface do all the work. A class that implements an
interface must implement all methods defined in that interface. An
interface has the ability to extend from other interfaces, and (unlike
classes) can extend from multiple interfaces. Furthermore, an interface
cannot be instantiated with the new operator
Java implement by two ways of creating threads: implementing an
interface and extending a class. All tasks must implement the run()
method, whether they are a subclass of Thread or implement the
Runnable interface.
The first method of creating a thread is to simply extend from the
Thread class. Do this only if the class you need executed as a thread does
not ever need to be extended from another class. The Thread class is
defined in the package java.lang, which needs to be imported so that our
classes are aware of its definition.

import java.lang.*;
public class test extends Thread
{
public void run()
{
....
}
}

The above example creates a new class Counter that extends the Thread
class and overrides the Thread.run() method for its own
implementation. The run() method is where all the work of the Counter
class thread is done. The same class can be created by implementing
Runnable:

import java.lang.*;
public class test implements Runnable
{
Thread T;
public void run()
RUN Method {
....
}
}

The only difference between the two methods is that by implementing


Runnable, there is greater flexibility in the creation of the class Counter.
In the above example, the opportunity still exists to extend the Counter
class, if needed. The majority of classes created that need to be run as a
thread will implement Runnable since they probably are extending some
other functionality from another class.

package java.lang;
Thread with Runnable
public interface Runnable
interface
{
public abstract void run();
}

That is all there is to the Runnable interface. An interface only provides a


design upon which classes should be implemented. In the case of the
Runnable interface, it forces the definition of only the run() method.
Therefore, most of the work is done in the Thread class
Q2. Develop a simple real life application program to illustrate the use of
multithread?
Ans:-

class NewThread implements Runnable

String name;

Thread t;

NewThread(String threadname){

name = threadname;

t = new Thread(this, name);

System.out.println("New Thread:" + t);

t.start();

public void run () {

try {

for(int i = 5; i > 0;i--) {

System.out.println(name + ":" + i);

Thread.sleep(1000);

}catch (InterruptedException e) {

System.out.println(name + "Interrupted");

System.out.println(name + "Exiting.");

}
class DemoJoin {

public static void main (String args [ ]) {

NewThread ob1 = new NewThread("One");

NewThread ob2 = new NewThread("Two");

NewThread ob3 = new NewThread("Three");

System.out.println("Thread One is alive:" + ob1.t.isAlive());

System.out.println("Thread Two is alive:" + ob2.t.isAlive());

System.out.println("Thread Three is alive:" + ob3.t.isAlive());

try {

System.out.println("Waiting for threads to finish.");

ob1.t.join();

ob2.t.join();

ob3.t.join();

}catch (InterruptedException e) {

System.out.println("Main Thread Interrupted");

System.out.println("Thread One is alive:" + ob1.t.isAlive());

System.out.println("Thread Two is alive:" + ob2.t.isAlive());

System.out.println("Thread Three is alive:" + ob3.t.isAlive());

System.out.println("Exiting Main Thread.");

}
OutPut:-

New Thread: Thread[One,5,main]

New Thread: Thread[Two,5,main]

New Thread: Thread[Three,5,main]

Thread One is alive: true

Thread Two is alive: true

Thread Three is alive: true

Waiting for threads to finish.

One: 5

Two: 5

Three: 5

One: 4

Two: 4

Three: 4

One: 3

Two: 3

Three: 3

One: 2

Two: 2

Three: 2

One: 1

Two: 1

Three: 1

Two exiting

Three exiting

One exiting

Thread One is alive: false

Thread Two is alive: false

Thread Three is alive: false


Q3.What is the difference between multiprogramming and multiprocessing
? what is to done to implements these in a program?
Ans:-
Multiprogramming :- Multiprogramming is one of the more basic types of
parallel processing that can be employed in many different environments.
Essentially, multiprogramming makes it possible for several programs to be
active at the same time, while still running through a single processor. The
functionality of multiprogramming in this environment involves a continual
process of sequentially accomplishing tasks associated with the function of one
program, then moving on to run a task associated with the next program.

Multiprogramming is very different from the multiprocessing because even


though there may be several programs currently active, the uniprocessor is
not simultaneously executing commands for all the programs. Instead, the
processor addresses each program, executes a single command, then moves
on to the next program in the queue. The previous program remains active,
but enters into a passive state until the uniprocessor returns to the front of
the queue and executes a second command.
Multiprocessing :-

Multiprocessing refers to an operating situation where the simultaneous


processing of programs takes place. This state of ongoing and coordinated
processing is usually achieved by interconnecting two or more computer
processors that make it possible to use the available resources to best
advantage. Many operating systems today are equipped with a
multiprocessing capability, although multiprogramming tends to be the more
common approach today.

The basic platform for multiprocessing allows for more than one computer to
be engaged in the used of the same programs at the same time. This means
that persons working at multiple work stations can access and work with data
contained within a given program. It is this level of functionality that makes it
possible for users in a work environment to effectively interact via a given
program.

Implement multiprocessing :-

You can create a thread to do multiprocessing. For example:


Thread t1=new Thread(1);
Thead t2=new Thread(2);
t1.run();
t2.run();

PART B
Q4.What are the two methods by which we can stop threads?
Ans:- The two thread methods for stoping thread is that
A) Stop method.
B) Interrupt:-
Publicvoidinterrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.

Example on Stop and Intruupt:-


// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}
private volatile Thread blinker;

public void stop() { Stop method


blinker = null;
}

public void run() {


Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}

// File Name : GuessANumber.java


// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}

// File Name : ThreadClassDemo.java


public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(hello);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
Output:-
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.

Q5:Write statements to create a file stream that concatenates two existing


files?
Ans:- The SequenceInputStream class allows you to concatenate multiple InputStreams.
The construction of a SequenceInputStream is different from any other InputStream. A
SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration
of InputStreams as its argument:

SequenceInputStream(InputStream first, InputStream second)


SequenceInputStream(Enumeration streamEnum)
Operationally, the class fulfills read requests from the first InputStream until it runs out and
then switches over to the second one. In the case of an Enumeration, it will continue through
all of the InputStreams until the end of the last one is reached. Here is a simple example that
uses a SequenceInputStream to output the contents of two files:
// Demonstrate sequenced input.
import java.io.*;
import java.util.*;
class InputStreamEnumerator implements Enumeration {
private Enumeration files;
public InputStreamEnumerator(Vector files) {
this.files = files.elements();
}
public boolean hasMoreElements() {
return files.hasMoreElements();
}
public Object nextElement() {
try {
return new FileInputStream(files.nextElement().toString());
} catch (Exception e) {

return null;
}
}
}
class SequenceInputStreamDemo {
public static void main(String args[]) throws Exception {
int c;
Vector files = new Vector();
files.addElement("/autoexec.bat");
files.addElement("/config.sys");
InputStreamEnumerator e = new InputStreamEnumerator(files);
InputStream input = new SequenceInputStream(e);
while ((c = input.read()) != -1) {
System.out.print((char) c);
}
input.close();
}
}

This example creates a Vector and then adds two filenames to it. It passes that vector of
names to the InputStreamEnumerator class, which is designed to provide a wrapper on
the vector where the elements returned are not the filenames but rather open
FileInputStreams on those names. The SequenceInputStream opens each file in turn,
and this example prints the contents of the two files.
Q6:-Write a program that will count the number of characters in a file?
Ans:-

import java.io.*;

public class WordCount{


private static void linecount(String fName, BufferedReader
in) throws IOException{
long numChar = 0;
long numLine=0;
long numWords = 0;
String line;
do{
line = in.readLine();
if (line != null){
numChar += line.length();
numWords += wordcount(line);
numLine++;
}
}while(line != null);
System.out.println("File Name: " + fName);
System.out.println("Number of characters: " + numChar);
System.out.println("Number of words: " + numWords);
System.out.println("Number of Lines: " + numLine);
}
private static void linecount(String fileName){
BufferedReader in = null;
try{
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
linecount(fileName,in);
}
catch(IOException e){
e.printStackTrace();
}
}
private static long wordcount(String line){
long numWords = 0;
int index = 0;
boolean prevWhiteSpace = true;
while(index < line.length()){
char c = line.charAt(index++);
boolean currWhiteSpace = Character.isWhitespace(c);
if(prevWhiteSpace && !currWhiteSpace){
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return numWords;
}
public static void main(String[] args){
long numChar = 0;
long numLine=0;
String line;
try{
if (args.length == 0)
{
BufferedReader in = new BufferedReader(new InputStreamRea
der(System.in));
line = in.readLine();
numChar = line.length();
if (numChar != 0){
numLine=1;
}
System.out.println("Number of characters: " + numChar);
System.out.println("Number of words: " + wordcount(line))
;
System.out.println("Number of lines: " + numLine);
}else{
for(int i = 0; i < args.length; i++){
linecount(args[i]);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
}

Output:-

Das könnte Ihnen auch gefallen