1. What is Thread?
1.a. Thread is a Light-weight ,its allow multiple activities within a single process.
1.b. All treads of a process share the common memory space, The process of execution multiple threads simultaneously is known as multi-threading.
2. Non-Thread Program vs Thread Program
2.a. Example Non-Thread Program.
public class WithoutThread {
// main method
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = “banana”;
String str2 = “papaya”;
ProcessClass proStr = new ProcessClass();
proStr.IterateRandomValue(str);
proStr.IterateRandomValue(str2);
}
}
class ProcessClass{
public void IterateRandomValue(String itr){
for (int i = 0; i < 5; i++) {
System.out.println(i + ” ” + itr );
}
}
}
OUTPUT in Console:
0 banana
1 banana
2 banana
3 banana
4 banana
0 papaya
1 papaya
2 papaya
3 papaya
4 papaya
Descriptions on without Thread class : without added thread class, it will execute the process one by one ( check the output program above, program banana will run first until its finish, and then, papaya program will be run ) – sequentially. the Process will taking longer time to finish the processing compare than extends Thread class or implements Runnable class.
2.b. Thread Program.
- the Functions of Java Threads is to allow multiple activities within a single process.
- To implement The Threads function we need to extends Thread Class or Implements Interface Runnable Class.
Example Program extend Thread class.
public class ThreadExample {
//Main Thread
public static void main(String[] args)
{
// TODO Auto-generated method stub
String str = “banana”;
String str2 = “papaya”;
// First Thread
ExtendThread firstThread = new ExtendThread(str);
firstThread.start();
//Second Tread
ExtendThread secondThread = new ExtendThread(str2);
secondThread.start();
}}
class ExtendThread extends Thread
{
private String strNew;ExtendThread(String str) {
strNew = new String(str);
}@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(i + ” ” + strNew);
}}
}
Output:
Starting Banana
Creating ..Papaya
Starting Papaya
Running..Banana
Thread : Banana,4
Running..Papaya
Thread : Papaya,4
Thread : Banana,3
Thread : Papaya,3
Thread : Banana,2
Thread : Papaya,2
Thread : Banana,1
Thread : Papaya,1