0% found this document useful (0 votes)
17 views

Book Program Java

Uploaded by

it254024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Book Program Java

Uploaded by

it254024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

class Book {

String title;
boolean isCompleted;

public Book(String title) {


super();
this.title = title;
}

public String getTitle() {


return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return isCompleted;
}
public void setCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}

class BookReader implements Runnable{

Book book;

public BookReader(Book book) {


super();
this.book = book;
}

@Override
public void run() {
synchronized (book) {
System.out.println(Thread.currentThread().getName()+" is waiting for the book to be
completed: "+book.getTitle());
try {
book.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": Book has been completed now!! you
can read it");
}
}

}
class BookWriter implements Runnable{

Book book;

public BookWriter(Book book) {


super();
this.book = book;
}

@Override
public void run() {
synchronized (book) {
System.out.println("Author is Starting book TO WRITE : " +book.getTitle() );
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
book.setCompleted(true);
System.out.println("Book has been completed now");

book.notify();
System.out.println("notify one reader");

}
}
}
public class ThreadInterCommunicationMain {

public static void main(String args[])


{
// Book object on which wait and notify method will be called
Book book=new Book("JAVA");
BookReader AReader=new BookReader(book);
BookReader BReader=new BookReader(book);

// BookReader threads which will wait for completion of book


Thread AThread=new Thread(AReader,"A");
Thread BThread=new Thread(BReader,"B");

AThread.start();
BThread.start();

// To ensure both readers started waiting for the book


try {
Thread.sleep(3000);
} catch (InterruptedException e) {

e.printStackTrace(); // The printStackTrace() method of Java. lang. Throwable class used to print
this Throwable along with other details like class name and line number where the exception occurred
means its backtrace
}
// BookWriter thread which will notify once book get completed
BookWriter bookWriter=new BookWriter(book);
Thread bookWriterThread=new Thread(bookWriter);
bookWriterThread.start();

A is waiting for the book to be completed: JAVA


B is waiting for the book to be completed: JAVA
Author is Starting book TO WRITE : JAVA
Book has been completed now
notify one reader
A: Book has been completed now!! you can read it
Java Thread suspend() method
The suspend() method of thread class puts the thread from running to waiting state. This method
is used if you want to stop the thread execution and start it again when a certain event occurs.
This method allows a thread to temporarily cease execution. The suspended thread can be
resumed using the resume() method.

Syntax
1. public final void suspend()

public class JavaSuspendExp extends Thread


{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaSuspendExp t1=new JavaSuspendExp ();
JavaSuspendExp t2=new JavaSuspendExp ();
JavaSuspendExp t3=new JavaSuspendExp ();
// call run() method
t1.start();
t2.start();
// suspend t2 thread
t2.suspend();
// call run() method
t2.start();
t3.start();
}
}
Java Threads | How to create a thread in
Java
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }
Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

hread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can
be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

You might also like