Adv Java
Programming

1. What Is the Java Technology 2. Points to keep in mind for pyramid. 3. Java Pyramid Program on type 1 4. Java Pyramid Program on type 2 5. Java Pyramid Programs on Type 3 6. Java Pyramid Programs on type 4 7. Java Pyramid Programs on type 5 8. Classes and Objects 9. Recursive functions 10. Constructors in Java 11. Method Overloading 12. Constructor Overloading 13. Inheritance in Java 14. Interface in Java 15. Method Overriding and Hiding Method 16. The final keyword 17. Exception Handling 18. Properties, System & Runtime Class in Java 19. Building Java GUI 20. Layout Managers 21. Menu Bar 22. Applets 23. Threading 24. Java Netwoking 25. Programs for Science and Engineer 26. Prg to demonstrate pre and post increment 27. Prg to convert Farenheit to Celsius temperature 28. Prg to convert kilogram to different units 29. Prg to calculate surface area and volume of sphere 30. Prg to calculate frequency 31. Prg to determine co-ordinate points 32. Prg to determine Equilateral, Isosceles or Scalene triangle 33. Prg to demonstrate conditional operator 34. Prg to calculate Final and initial interest amount 35. Prg to separate entered number 36. Prg to examine while loops and conditions 37. Prg to calculate number of year 38. Prg to find Armstrong number or not 39. Prg to find all Armstrong number 40. Prg to find limited Armstrong number 41. Prg to find Armstrong number using user defined function 42. Prg to find frequency of student 43. Prg to find maximum and minimum number 44. Prg to print number triangle 45. Prg to print vertical number triangle 46. Prg to print number triangle 47. Prg to print binary right angle triangle 48. Prg to print * triangle 49. Prg to to print rhombus 50. Prg to print entered number triangle 51. Prg to to find nCr and nPr 52. Prg to enter an element in array 53. Prg to sort number using array 54. Prg to find the position of element in array 55. Prg to find the position of element in array using boolean flag 56. Prg to add one extra element in an array 57. Prg to find the equation of line 58. Prg to find the common element from two array 59. Prg to find the highest scorer 60. Prg to create a square of number 61. Prg to create Pascal triangle 62. Prg to subtraction, multiplication and division using methods and classes 63. Prg to determine salary grade 64. Prg for complex number 65. Prg to calculate area 66. Prg for Greatest Common Divisior 67. Prg for displaying studenta mark sheet 68. Prg for demonstrating inheritance 69. Prg to calculate area of triangle 70. Prg for calculating volume of sphere or hemisphere 71. Prg for demonstrate classes 72. Prg for employee details 73. Prg for demonstrating super and base class 74. Prg for Bank Account 75. Prg for professor and student details 76. Prg for Addition, Multiplication and finding Transpose of two matrix 77. Prg for counting number of words in a string 78. Prg to count number of vowels and consonants in a string 79. Prg to fine number of upper case, lower case, white spaces and digit in a string 80. Prg to fine number of upper case, lower case, white spaces and digit in a string without inbuilt function 81. Prg to arrange a string in alphabetic order 82. Prg to count the number of character occurrence in a string 83. Prg to find the string length and character position 84. Prg for converting first character of word into upper case 85. Prg for demonstrating vectors for manipulating records 86. Prg for manupulting items record using vectors 87. Prg for bank transaction 88. Prg for counting number of days between any two different date 89. Prg for exception handling 90. Prg for throwing exception 91. Prg for exception 92. Prg to throw exception when number is invalid 93. Prg for renaming the current thread 94. Prg for demonstrating strat method of thread 95. Prg to demonstrate sleep and and join method of thread 96. Prg to demonstrate yield method of thread 97. Prg for demonstrating thread in class inheritance 98. Threading program using runnable interface 99. Thread program using sleep 100. Java Applet program for creating fancy round eye 101. Java Applet program for creating fancy face 102. Java Applet program for drawing string 103. Java Applet program for creating fancy face 104. Java Applet program for displaying fancy fonts 105. Java Applet program for drawing and filling rectangle 106. Java Applet program for creating house 107. Java Applet program to show lifecycle of applet 108. Java Applet program for creating polygon 109. Java Applet program for creating rectangle 110. Java Applet program for drawing line 111. Java Applet program for getting applet width and height 112. Interview Question & Answer part 1 113. Interview Question & Answer part 2 114. Interview Question & Answer part 3 115. Interview Question & Answer part 4 116. Interview Question & Answer part 5 117. Interview Question & Answer part 6 118. Interview Question & Answer part 7 119. Interview Question & Answer part 8 120. Interview Question & Answer part 9 121. Interview Question & Answer part 10 122. Interview Question & Answer part 11
Pr.Pg Next Pg

Threading tutorials

  • A thread is a sequential path of code execution within a program. And each thread has its own local variables, program counter and lifetime.

 

Process

  • A process is an instance of a computer program that is executed sequentially.

  • It is a collection of instructions which are executed simultaneously at the rum time.

  • Thus several processes may be associated with the same program.

  • For example, to check the spellingis a single process in the Word Processor program and you can also use other processes like printing, formatting, drawing, etc. associated with this program.

Thread

  • A thread is a lightweight process which exist within a program and executed to perform a special task.

  • Several threads of execution may be associated with a single process.

  • Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process.

  • In Java Programming language,  thread is a sequential path of code execution within a program.

  • Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete.

  • It exists in a common memory space and can share both data and code of a program.

  • Threading concept is very important in Java through which we can increase the speed of any application.

  • You can see diagram shown below in which a thread is executed along with its several operations with in a single process. 

Single process

Operation 1

Operation 2

.

.

.

Opeartion n

Main Thread

  • When any standalone application is running, it firstly execute the main() method runs in a one thread, called the main thread.

  • If no other threads are created by the main thread, then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads.

  • The main() method execution can finish, but the program will keep running until the all threads have complete its execution.

 

Java Thread Model

  • The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU time.

  • This wastes CPU time. It can also result in one part of a program dominating the system and preventing any other events from being processed. In general, in a singled-threaded environment, when a thread blocks that is, suspends execution because it is waiting for some resource, the entire program stops running.

  • Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. Arunning thread can be suspended, which temporarily suspends its activity. Asuspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

 

Life Cycle of Thread

Thread Life Cycle

 

  1. New state: After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
     

  2. Runnable (Ready-to-run) state: A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 
     

  3. Running state: A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
     

  4. Dead state: A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

  5. Blocked: A thread can enter in this state because of waiting the resources that are hold by another thread.

 

Difference between thread and process

Thread

Process

Threads are light weight and use the minimum available system resources as a whole and can execute simultaneously to acheive a given task.

Process are heavy weight programs which consume considerable amount of memory for execution and are heavily dependent on system resources for their execution

Thread is a  single execution sequence within a process

A Procees is an execution of program

Threads share memory with other  threads running in the same process.

Process are fully isolated from each other

If a thread stops then process would not stop.

If process is stop then all active threads inside that process will be stoped or killed immediately.

 

 

Creating Thread in Java

  • In Java you can create thread in two ways as below:

    1. You can create thread by implementing the Runnable interface.

    2. You can also create thread by extending the Thread class, itself.

  • Below table shows the different methodís of threadís

 

Method

Description

getName

Use for obtaining the threadís name.

getPriority

Use for obtaining the threadís priority.

isAlive

Use to determine if a thread is still running.

join

Wait for a thread to terminate.

run

Entry point for the thread.

sleep

Use for suspend the thread for a period of time.

start

Use for starting the thread by calling its run method.

 

Implement Runnable Interface:

  • The easiest way to create a thread is to create a class that implements the Runnable interface.

  • Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable.

  • To implement Runnable, a class need only implement a single method called run( ), which is declared as below:

public void run()

{

//code

}


 

Example: Java program to create thread by implementing Runnable interface

 Sam Madam

//Program name RunnableDemo.java

//Java program to create thread by implementing Runnable interface

public class RunnableDemo

{

public static void main(String[] args)

{

DemoThread dt=new DemoThread();

Thread t=new Thread(dt);

t.start();

}

}

 

class DemoThread implements Runnable

{

public void run()

{

Thread t = Thread.currentThread();

System.out.println("Current thread: " + t);

t.setName("My Thread");

System.out.println("After name change: " + t);

try {

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

System.out.println(n);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println("Main thread interrupted");

}

}

}

Output

Current thread: Thread[Thread-0,5,main]

After name change: Thread[My Thread,5,main]

5

4

3

2

1

 

Extending Thread class:

  • The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.

  • The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

  • Below is the RunnableDemo.java program converted into ExtendThreadDemo.java:

 

 

Example: Java program to create thread by extending Thread class

 Sam Madam

//Program name ExtendThreadDemo.java

//Java program to create thread by extending Thread class

public class ExtendThreadDemo

{

public static void main(String[] args)

{

ThreadDemo th=new ThreadDemo();

Thread t=new Thread(th);

t.start();

}

}

 

class ThreadDemo extends Thread

{

public void run()

{

Thread t = Thread.currentThread();

System.out.println("Current thread: " + t);

t.setName("My Thread");

System.out.println("After name change: " + t);

try {

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

System.out.println(n);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println("Main thread interrupted");

}

}

}

Output

Current thread: Thread[Thread-1,5,main]

After name change: Thread[My Thread,5,main]

5

4

3

2

1

 

 

Example: Java program to demonstrate Thread methodís(sleep and join)

 Sam Madam

//Program name ThreadsMethodDemo.java

//Java program to demonstrate Thread methodís(sleep and join)

class AB extends Thread

{

public void run()

{

for(char ch = 'a'; ch <= 'z'; ch++)

{

System.out.print(ch+" ");

try

{

Thread.sleep(500);

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

System.out.println("\n");

}

}

class BB extends Thread

{

public void run()

{

for(int i = 1; i <= 26; i++)

{

System.out.print(i+" ");

try{Thread.sleep(500);}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

}

}

public class ThreadsMethodDemo

{

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

{

AB x = new AB();

BB y = new BB();

x.start();

y.start();

if(x.isAlive())x.join();

if(y.isAlive())y.join();

System.out.print("Main Terminated");

}

}

Output

a 1 b 2 c 3 d 4 5 e 6 f 7 g 8 h 9 i j 10 11 k l 12 13 m 14 n o 15 p 16 17 q r 18 19 s t 20 21 u v 22 23 w x 24 25 y 26 z

Main Terminated

 

Thread Priorities

  • Java assigns to each thread a priority that determines how that thread should be treated with respect to the others.

  • Thread priorities are integers that specify the relative priority of one thread to another.

  • As an absolute value, a priority is meaningless; a higher-priority thread doesnít run any faster than a lower-priority thread if it is the only thread running.

  • Instead, a threadís priority is used to decide when to switch from one running thread to the next. This is called a context switch.

  • You can set priority of thread by using below method

setPriority(int priority);

  • The above method sets the priority of Threadobject. The possible values are between 1 and 10. However, developers are encouraged to use the following three values

  • Thread.NORM_PRIORITY,Thread.MIN_PRIORITY, and Thread.MAX_PRIORITY whose values are 5, 1, and 10, respectively.

  • Below program demonstrate the thread priority:

 

 

Example: Java program to demonstrate setPriority

 Sam Madam

//Program name ThreadPriorities.java

// Java program to demonstrate setPriority

class MyRun extends Thread

{

int init, fin, delay;

MyRun (int init, int fin, int delay)

{

this.init = init;

this.fin = fin;

this.delay = delay;

}

 

public void run()

{

for(int i = init; i <= fin; i++)

{

System.out.println(i);

try

{

Thread.sleep(delay);

}

catch (InterruptedException e) {}

}

System.out.println("Thread Terminated");

}

}

class ThreadPriorities

{

public static void main (String args [])

{

MyRun r1 = new MyRun(10, 20, 100);

MyRun r2 = new MyRun(21, 30, 300);

MyRun r3 = new MyRun(31, 40, 500);

Thread x = new Thread(r1); x.setPriority(1);

Thread y = new Thread(r2); y.setPriority(5);

Thread z = new Thread(r3); z.setPriority(10);

x.start();

y.start();

z.start();

System.out.println("Main Terminated");

}

}

Output

31

Main Terminated

21

10

11

22

12

32

13

14

23

15

16

17

24

33

18

19

20

25

Thread Terminated

34

26

27

35

28

29

36

30

37

Thread Terminated

38

39

40

Thread Terminated

Pr.Pg border                                              Next Pg