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

java_unit2 (1)

Uploaded by

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

java_unit2 (1)

Uploaded by

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

Multithreading

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

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common 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 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 exception occur in a single
thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:

o Process-based Multitasking(Multiprocessing)

o Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process have its own address in memory i.e. each process allocates separate
memory area.
o Process is heavyweight.

o Cost of communication between the process is high.

o Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.

o Thread is lightweight.

o Cost of communication between the thread is low.

What is Thread in java


A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.

Note: At a time one thread is executed only.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New

2. Runnable

3. Running

4. Non-Runnable (Blocked)

5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.

3) Running
The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.

How to create thread


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:

o Thread()

o Thread(String name)

o Thread(Runnable r)

o 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:

start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).

o The thread moves from New state to the Runnable state.


o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...

2) Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
10. }
11. }
Output:thread is running...

If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

Difference between preemptive scheduling and time slicing


Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.

Sleep method in java


The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java


The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException

o public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java


class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
10. TestSleepMethod1 t2=new TestSleepMethod1();
11.
12. t1.start();
13. t2.start();
14. }
15. }

Output:

1
1
2
2
3
3
4
4

As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time,the thread shedular picks up another thread and so on.

The join() method


The join() method waits for a thread to die. In other words, it causes the currently running threads to
stop executing until the thread it joins with completes its task.

Syntax:

public void join()throws InterruptedException


public void join(long milliseconds)throws InterruptedException
Example of join() method
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
10. public static void main(String args[]){
11. TestJoinMethod1 t1=new TestJoinMethod1();
12. TestJoinMethod1 t2=new TestJoinMethod1();
13. TestJoinMethod1 t3=new TestJoinMethod1();
14. t1.start();
15. try{
16. t1.join();
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22. }
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
Example of join(long miliseconds) method
class TestJoinMethod2 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
10. public static void main(String args[]){
11. TestJoinMethod2 t1=new TestJoinMethod2();
12. TestJoinMethod2 t2=new TestJoinMethod2();
13. TestJoinMethod2 t3=new TestJoinMethod2();
14. t1.start();
15. try{
16. t1.join(1500);
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22. }
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3
starts executing.
23.

getName(),setName(String) and getId() method:

public String getName()


public void setName(String name)
public long getId()
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Sonoo Jaiswal");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...

19.

The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.
Syntax:

public static Thread currentThread()


Example of currentThread() method
class TestJoinMethod4 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
TestJoinMethod4 t1=new TestJoinMethod4();
TestJoinMethod4 t2=new TestJoinMethod4();

10. t1.start();
11. t2.start();
12. }
13. }
Output:Thread-0
Thread-1

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defiend in Thread class:


1. public static int MIN_PRIORITY

2. public static int NORM_PRIORITY

3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value
of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread{


public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Daemon Thread
Daemon thread in java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides
information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java


o It provides services to user threads for background supporting tasks. It has no role in life than
to serve user threads.
o Its life depends on user threads.

o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?


The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM
terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) thread.

2) public boolean isDaemon() is used to check that current is daemon.


Simple example of Daemon thread in java
File: MyThread.java

public class TestDaemonThread1 extends Thread{


public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
10. public static void main(String[] args){
11. TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
12. TestDaemonThread1 t2=new TestDaemonThread1();
13. TestDaemonThread1 t3=new TestDaemonThread1();
14.
15. t1.setDaemon(true);//now t1 is daemon thread
16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. }
21. }

Output
daemon thread work
user thread work
user thread work

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

How can an object be unreferenced?


There are many ways:

o By nulling the reference

o By assigning a reference to another

o By annonymous object etc.

1) By nulling a reference:

Employee e=new Employee();


e=null;

2) By assigning a reference to another:

Employee e1=new Employee();


Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:

protected void finalize(){}


Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if
you have created any object without new, you can use finalize method to perform cleanup processing
(destroying remaining objects).

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.

public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread
calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java


public class TestGarbage1{

public void finalize(){System.out.println("object is garbage collected");}


public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
10. }
11. }
object is garbage collected
object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Unit2
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:

o It works at client side so less response time.

o Secured

o It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to execute applet.

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.

Lifecycle of Java Applet

1. Applet is initialized.

2. Applet is started.
3. Applet is painted.

4. Applet is stopped.

5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.

2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.

3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.

4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

10. }

Note: class must be public because its object is created by Java Plugin software that resides on the
browser.

myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for
testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:

public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.

2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

import java.awt.*;
import java.applet.*;

public class DisplayImage extends Applet {

Image picture;

public void init() {


10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

myapplet.html

<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the
simple example of event handling in applet that prints a message by click on the button.

Example of EventHandling in applet:


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;

public void init(){


tf=new TextField();
tf.setBounds(30,40,150,20);
10.
11. b=new Button("Click");
12. b.setBounds(80,150,60,50);
13.
14. add(b);add(tf);
15. b.addActionListener(this);
16.
17. setLayout(null);
18. }
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome");
21. }
22. }
In the above example, we have created all the controls in init() method because it is invoked
only once.

myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body> </html>

Java AWT Tutorial


Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in
java.

Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavyweight i.e. its components uses the resources of system.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.

Java AWT Hierarchy


Container
The Container is a component in AWT that can contain other components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog
and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class


Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)

o By creating the object of Frame class (association)

Simple example of AWT by inheritance


import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position

add(b);//adding button into frame


10. setSize(300,300);//frame size 300 width and 300 height
11. setLayout(null);//no layout manager
12. setVisible(true);//now frame will be visible, by default not visible
13. }
14. public static void main(String args[]){
15. First f=new First();
16. }}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.

14.

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.
Event classes and Listener interfaces:

Event Classes Listener Interfaces


ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Implement the Listener interface and overrides its methods

2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods. For
example:

o Button

o public void addActionListener(ActionListener a){}

o MenuItem

o public void addActionListener(ActionListener a){}


o TextField

o public void addActionListener(ActionListener a){}

o public void addTextListener(TextListener a){}

o TextArea

o public void addTextListener(TextListener a){}

o Checkbox

o public void addItemListener(ItemListener a){}

o Choice

o public void addItemListener(ItemListener a){}

o List

o public void addActionListener(ActionListener a){}

o public void addItemListener(ItemListener a){}

EventHandling Codes:

We can put the event handling code into one of the following places:

1. Same class

2. Other class

3. Annonymous class

Example of event handling within class:

import java.awt.*;
import java.awt.event.*;

class AEvent extends Frame implements ActionListener{


TextField tf;
AEvent(){

tf=new TextField();
tf.setBounds(60,50,170,20);
10.
11. Button b=new Button("click me");
12. b.setBounds(100,120,80,30);
13.
14. b.addActionListener(this);
15.
16. add(b);
17. add(tf);
18.
19. setSize(300,300);
20. setLayout(null);
21. setVisible(true);
22.
23. }
24.
25. public void actionPerformed(ActionEvent e){
26. tf.setText("Welcome");
27. }
28.
29. public static void main(String args[]){
30. new AEvent();
31. }
32. }

15. public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.

You might also like