Java3

                     Subscribe Our  Youtube Channel

                              

   Unit-III

MULTITHREADING IN JAVA

1.What is thread?Explain process based ,thread based multi threading?

Ans:

A thread is a single sequential flow of  control within a program. A single program having multiple threads, executing concurrently, can be termed as multithreaded program.

 

Let us go to the basics of multithreading, which is actually a form of multitasking. Multitasking can either be process-based or thread-based

Process-based If we assume programs as processes, then process based multitasking is nothing but execution of more than one program concurrently. Processes are heavyweight tasks. In process-based multitasking, different processes are different programs, thus they share different address spaces.  

Thread-based 

Thread-based multitasking is executing a program having more than one thread, performing different tasks simultaneously. Threads are lightweight tasks.In thread-based multitasking, different threads are part of the same program, thus they share the same address space . Thread-based multitasking will be called  as multithreading.        

***  The objective of all forms of multitasking including multithreading is to utilize the idle time of the CPU.  

 Ideally a CPU should always be processing something.  

 The idle time of CPU can be minimized using multitasking. 

 

MAIN THREAD 

2.What is main thread? Explain? 

Ans:  Every Java program has a thread, that is main thread.  

 The JVM creates the main thread and calls the program‘s main()method from within that thread.  

 The JVM also creates some invisible threads, for  tasks such as  garbage collection etc..  The main thread spawns the other threads. These spawned threads are called child threads.  

 This main thread is always the last to finish executing because it is responsible for releasing the resources. 

 A static method, currentThread(), is used to return a reference to the current thread. The main thread can be controlled by this reference only. 

 We could also change the name of the main thread from main to any new name. 

 

Example Renaming a Thread  class MainThreadDemo  

{  public static void main (String args[] )  

{  

Thread threadObj = Thread.currentThread(); System.out.println("Current thread: " +threadObj);  

threadObj.setName("New Thread");  System.out.println("Renamed Thread: " +threadObj); 

Output Current thread: 

Thread[main, 5, main]    

Renamed Thread: Thread[New Thread, 5, main] 

If we see the output now, the information within the square brackets is the signature of the thread. The first element in the bracket is the name of the thread. The second element signifies the thread priority.The last element in the bracket is the group name for threads to which the thread belongs.


3.Explain Various ways of creating threads in java?

Ans:

The ways to create a new thread:

·   By inheriting the Thread class

· By implementing the Runnable interface

By Inheriting the Thread Class

Threads can be created by inheriting the java.lang.Thread class. All the thread methods belonging to the Thread class can be used in the program because of the extension (inheritance).

Steps to be followed for thread creation:

· Declaring a Class Any new class can be declared to extend the Thread class, thus inheriting all the functionalities of the Thread class.

classNewThread extends Thread

{

......

}

Here, we have a new type of thread, named as ‘NewThread’.

· Overriding the run() Method The run() method has to be overridden by writing codes required for the thread. The thread behaves as per this code segment. A typical run() method would look like

public void run( )

{

//code segment providing the functionality of thread

}

· The third part talks about the start() method, which is required to create and initiate an instance of our Thread class. The following piece of code is responsible for the same:

newThread thread1 = new newThread();

thread1.start();

The first line creates an instance of the class NewThread, where the object is just created.

The thread is in newborn state. Second line, which calls the start() method, moves the thread to runnable state, where the Java Runtime will schedule the thread to run by invoking the run() method. Now the thread is said to be in running state.

                                                                                                                                       

Implementing the Runnable Interface

Runnable Interface actually implemented by class Thread in the package java.lang. This interface is declared  as,

 

public interface Runnable

 

The interface needs to be implemented by any class whose instance is to be executed by a thread.

The implementing class must also override a method named as run(), defined as the only method in the Runnable interface as,

public void run( )

{

......

}

 

The object’s run() method is called automatically whenever the thread is scheduled for execution by the thread scheduler.

The functionality of the thread depends on the code written within this run() method. Other methods can also be called from run(). Not only this, use of other classes and declaration of variables, just like the main thread, are also possible inside run(). The thread will stop as soon as the run() exits.

 

The Thread class has the following consructors.

·  Thread(Runnable threadObj)

· Thread(Runnable threadObj, String threadName)

·Thread(ThreadGroup threadGroup, Runnable threadObj)

·Thread(ThreadGroup threadGroup, Runnable threadObj, String threadName)

 

The above threadObj is a reference to an instance of a class that implements the Runnable interface and overrides the run() method. This defines where the execution will begin.

threadName is the name of the thread.

The third argument, threadGroup is the group name to which the thread belongs.

                                                                                               



4.Explain Thread life cycle with diagram?

Ans:

New In this state, a new thread is created but not started. The following line of code is responsible for the same

 

Thread threadObj = new ThreadDemo();

Runnable

In this state, a thread is ready for execution by the JVM. It represents the running state of the thread, as well. Ready state of a thread can be defined as it is ready for execution but it might be in the queue, waiting for the operating system to provide it the required resource, like processor. Once a thread is actually being executed by the processor then it is termed as “Running”. From ‘New’ state the thread might move to the ‘Runnable’ state on execution of the following statements:

 

Thread threadObj = new ThreadDemo();

threadObj.start();

 

As soon as start() is called, the thread is allotted the system resource as per the scheduling done by the Java Runtime Environment. Now the thread has entered into the runnable state.

 

Not Runnable From runnable state, a thread might move to the not runnable state, as shown in Fig. This state is categorize the three valid states of Java. A thread which is in any of these three states can be assumed to be in ‘not runnable’ state.

These three states are WAITING, TIMED_WAITING, and BLOCKED.

Waiting In this state, a thread is waiting indefinitely for another thread to perform a particular action (i.e., notify). Threads can move into this state either by calling the methods Object.wait() (without time out) or Thread.join() (without time out).

Timed_Waiting  In this state, the thread is waiting for another thread to perform an action (notify) up to a specified waiting time. A thread can get into this state by calling either of these methods:

Thread.sleep(), Object.wait(), and Thread.join() (all these methods should be called with time out specified).

Blocked In this state, a resource cannot be accessed because it is being used by another thread.

A thread can get into this state by calling Object.wait() method.

 

Terminated

This state is reached when the thread has finished its execution. A thread can move to ‘Terminated’ state, from any of the above mentioned states. In this state, the thread is dead. The death of a thread can either be natural or forceful.

A thread can always be interrupted by using interrupt().

Output:

Thread -0 is New

Thread -0 is Runnable

Thread -0 is terminated



5.Explain java.io.FILE CLASS with an example?

Ans:

The java.io.File class is worth mentioning, as it neither belongs to the byte stream nor the character stream used for reading or writing a file. This class is used to know the properties of a file-like path of the file, whether the file exists or not, whether the file is a file or a directory, and length of the file. Let us take a look at the example of File class.

 Example

import java.io.*;

 class FileDemo {

 public static void main(String args[]) {

 File f = new File(args[0]);

 System.out.println("File exists: "+f.exists());

System.out.println("File can be read:"+f.canRead());

System.out.println("File can be written: "+f.canWrite());

System.out.println("File can be executed:"+f.canExecute());

System.out.println("File name: "+f.getName());

System.out.println("parent of File:"+f.getParent());

System.out.println("path of the File:"+f.getPath());

System.out.println("Hidden File: "+f.isHidden());

System.out.println("length of the fi le: "+f.length());

System.out.println("last modifi ed time: "+f.lastModified());

 System.out.println("it is a File: "+f.isFile());

 if(f.isDirectory()) {

System.out.println(f.getPath()+ "is a directory");

 String l[] = f.list();

System.out.println("\nDirectory Listing for "+f.getPath() + "is:");

for(String a:l) {

 File f1 = new File(f.getPath() + "/" +a);

 if(f1.isDirectory()) {

 System.out.println(a+ "is a directory");

 f1 = null;

}

 else

 { System.out.println(a+ "is a File");

 f1 = null;

}

}

}}}

 

Output

For ‘Sample.txt’ file

C:\javabook\programs\chap09>java FileDemo sample.txt

File exists: true File can be read: true

File can be written: true

File can be executed: true

File name: sample.txt

parent of File: null

path of the File: sample.txt

Hidden File: false

length of the fi le: 105

last modifi ed time: 1236860698637

it is a File: true

 

For ‘programs’ directory

C:\javabook\programs\chap09>java FileDemo

c:\javabook\programs

File exists: true

File can be read: true

File can be written: true

File can be executed: true

File name: programs

parent of File: c:\javabook

path of the File: c:\javabook\programs

Hidden File: false

length of the fi le: 12288

last modifi ed time: 1237062320960

it is a File: false

c:\javabook\programs is a Directory

Directory Listing for c:\javabook\programs is:

A.class is a File

B.class is a File

chap 6 is a directory

chap 7 is a directory

chap09 is a directory

chap3 is a directory


6.Explain FileInputStream , FileOutputStream with example?

Ans:

FILE INPUTSTREAM CLASS

FileInputStream (inherits InputStream) class is used for reading a file

Methods of FileInputStream Class

int available()   Returns the number of remaining bytes that can be read from this input stream.

void close()      Closes this file input stream and releases all system resources.

void finalize()    Ensures that the close method of this file input stream is called when there are no more references to it.

FileChannel getChannel()   Returns the unique FileChannel object associated with this file input stream.

final FileDescriptor getFD()   Returns the FileDescriptor object that represents the connection to the actual file in the fi le system being used by this FilelnputStream.

int read()       Reads a byte of data from this input stream.

long skip(long n)     Skips over and discards n bytes of data from the input stream.

 

 File Input Stream Example

import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=0;

while((i=fin.read())!=-1){

System.out.print((char)i);

}

fin.close();

}

catch(Exception e){System.out.println(e);}

}

}

Output:

welcome to world

 

FILE OUTPUTSTREAM CLASS

FileOutput-Stream (inherits OutputStream) is used for writing to a file.

 

Methods of FileOutputStream Class

 

void close()  Closes this file output stream and releases all system resources.

protected void finalize() Cleans up the connection to the file.

FileChannel getChannel()    Returns the unique FileChannel object associated with this stream.

FileDescriptor getFD()         Returns the file descriptor associated with this output stream.

void write (byte [] b)         Writes bytes from the specified byte array to this fi le output stream.

void write(int b)                 Writes the specified byte to this file output stream.

 

FileOutputStream Example

import java.io.FileOutputStream;

public class FileOutputStreamExample {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

String s="Welcome to World.";

byte b[]=s.getBytes();                                    //converting string into byte array

fout.write(b);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

}

}

Output:

Success….

The content of a text file testout.txt is set with the data Welcome to World.

testout.txt.

 welcome to world


7.Explain Buffered  Input/Output Stream Classes?

Ans:

BufferedOutput Stream Class

BufferedOutputStream  class implements a buffered output stream that can be used to write bytes to the underlying output stream without making unnecessary calls to the underlying system for each byte. 

 

Methods of BufferedOutputStream Class

void flush ()    Flushes the output stream.

void write(byte[] b,int off, int len)   Writes the specified number of bytes (len) to the output stream starting from the offset (off).

void write(int b)    Write the specified byte to the output stream.

 

Example Buffered Input/Output

import java.io.*;

class BufferedInOutStreamDemo {

public static void main(String args[]) throws IOException

{

FileInputStream fis = new FileInputStream(args[0]);

BufferedInputStream bis = new BufferedInputStream(fi s);

int n = fis.available();

bis.mark(n);

System.out.println ("Marked the stream");

byte b[] = new byte[n];

byte b1[] = new byte[n];

bis.read(b);

System.out.println("Contents of "+args[0]+ ":"+new String(b));

System.out.println("Resetting the stream");

bis.reset();

System.out.println("Reading the stream again from the marked point");

bis.read(b1);

System.out.println(new String(b1));

bis.close();

fis.close();

System.out.println ("Writing contents to : "+args[1]);

 FileOutputStream fos = new FileOutputStream(args[1]);

 BufferedOutputStream out = new BufferedOutputStream(fos);

out.write(b);

System.out.println ("Contents written");

out.close(); fos.close();

}}

Output

C:\javabok\programs\chap09>java BufferedInOutStreamDemo sample.txt Demo.txt

Marked the stream

Contents of sample.txt: This is my sample file

Resetting the stream

Reading the stream again from the marked point

This is my sample fi le

Writing contents to : Demo.txt


8.Explain Randomly Accessing A FILE With An Example?

Ans:

RandomAccessFile gives an opportunity to read or write files from a specific location. This class has a method named seek (long pos) that sets the file pointer at the specified position (pos).Now any read/write operation on the file will start from this marked position.

 

Methods

void close()   Closes this random access file stream.

long length()    Returns the length of the file.                                   

int read()    Reads a byte of data from this file.       

final boolean readBoolean()   Reads a boolean from this file.

byte readByte()   Reads a signed eight-bit value from this file.

final char ceadChar()    Reads a character from this file.

final double readDouble()    Reads a double from this file.

final float readFloat()     Reads a float from this file.

void seek(long pos)         Sets the file-pointer, measured from the beginning of this fi le, at which the next read or write operation occurs.           

void setLength (long newLength)    Sets the length of this fi le.

int skipBytes(int n)      Skips n bytes of input discarding skipped bytes.    

 

Random Access File

import java.io.*;

class RandomAccessFileDemo {

public static void main(String args[]) throws IOException

{

System.out.println("Opening the fi le in read write mode");

RandomAccessFile raf = new RandomAccessFile ("Sample.txt","rw");

raf.seek(raf.length());

String str = "\nContents appended using RandomAccessFile";

 System.out.println("Appending contents to fi le");

raf.write(str.getBytes());

System.out.println("Contents appended");

System.out.println("Reading the contents of the fi le....");

 raf.seek(0);

while((str = raf.readLine())!= null)

System.out.println(str);

raf.close();

}}

Output

C:\javabook\programs\CHAP09~1>java RandomAccessFileDemo

Opening the fi le in read write mode

Appending contents to fi le

Contents appended

Reading the contents of the fi le....

This is my sample File

Contents appended using RandomAccessFile

Contents written



No comments:

Post a Comment