Thread Methods
To know thread and thread behavior should know about some
methods like run(), start(), sleep(), join(), wait(), notify() and notifyAll().
run() method
a.
Method defines in java.lang.Runnable interface.
b.
java.lang.Thread class implements
java.lang.Runnable interface.
c.
Code defines in this method to run in different
thread.
d.
You can overload run() method but those will not
be useful to start new thread.
start() method
a.
Method defines in java.lang.Thread class.
b.
This method starts a new thread.
sleep() method
a.
Method defines in java.lang.Thread class.
b.
It is used to suspend the running thread for
specific time period.
c.
It pusses the thread from running state to waiting
or suspended state.
d.
It is not release the loc during the waiting or
suspended time period.
e.
It throws exception (InteruptedException).
join() method
a.
Method defines in java.lang.Thread class.
b.
It uses to join the thread at the end of the
execution of the thread.
c.
It suspends current thread until specific thread
execution completed.
d.
It throws exception (InteruptedException).
wait() method
a.
Method defines in java.lang.Object class.
b.
It uses to suspend the thread until the locking
object is released by other thread.
c.
Without notify() or notifyAll() wait will be
forever.
d.
It throws exception (InteruptedException).
e.
After invoking wait() method locking object will
be released for other threads and it will be again acquire for further
execution of the thread.
f.
There should be notify for every wait() method.
notify() and notifyAll() method
a.
Method defines in java.lang.Object class.
b.
It notify about the free of the locking object to
waiting thread or all threads.
Thread Example#3
This example for join() function using three threads.
§
Create thread class extends java.lang.Thread
class. (file name: JoinMyThreadClass1.java)
public class JoinMyThreadClass1 implements Runnable {
@Override
public void run() {
System.out.println("Start:" + Thread.currentThread().getName());
JoinMyThreadClass2
jmtc2 = new JoinMyThreadClass2();
Thread t2 = new Thread(jmtc2);
t2.start();
try {
t2.join();
} catch (Exception e)
{}
for (int i = 0; i <
5; i++) {
System.out.println(this.getClass().getName()
+ "
/ "
+
Thread.currentThread().getName());
try{
Thread.sleep(800);
}catch (Exception e)
{}
}
System.out.println("Stop:" + Thread.currentThread().getName());
}
}
§
Create thread class extends java.lang.Thread
class. (file name: JoinMyThreadClass2.java)
public class JoinMyThreadClass2 implements Runnable {
@Override
public void run() {
System.out.println("Start:" + Thread.currentThread().getName());
for (int i = 0; i <
5; i++) {
System.out.println(this.getClass().getName()
+ "
/ "
+
Thread.currentThread().getName());
try{
Thread.sleep(800);
}catch (Exception e) {
}
}
System.out.println("Stop:" + Thread.currentThread().getName());
}
}
§
Create Main method class (file name: JoinMyThreadMain.java)
public class JoinMyThreadMain {
public static void main(String[]
args) {
Thread tm1 = Thread.currentThread();
System.out.println("Start:" +
tm1.getName());
JoinMyThreadClass1
jmtc1 = new JoinMyThreadClass1();
Thread t1 = new Thread(jmtc1);
t1.start();
try {
t1.join();
} catch (Exception e) {
}
for (int i = 0; i <
5; i++) {
System.out.println(JoinMyThreadMain.class.getClass().getName()
+ " /
" + tm1.getName());
try {
tm1.sleep(500);
} catch (Exception e) {
}
}
System.out.println("Stop:" +
tm1.getName());
}
}
§
Run and see output
Start:main
Start:Thread-0
Start:Thread-1
pack.thread.JoinMyThreadClass2 / Thread-1
pack.thread.JoinMyThreadClass2 / Thread-1
pack.thread.JoinMyThreadClass2 / Thread-1
pack.thread.JoinMyThreadClass2 / Thread-1
pack.thread.JoinMyThreadClass2 / Thread-1
Stop:Thread-1
pack.thread.JoinMyThreadClass1 / Thread-0
pack.thread.JoinMyThreadClass1 / Thread-0
pack.thread.JoinMyThreadClass1 / Thread-0
pack.thread.JoinMyThreadClass1 / Thread-0
pack.thread.JoinMyThreadClass1 / Thread-0
Stop:Thread-0
java.lang.Class / main
java.lang.Class / main
java.lang.Class / main
java.lang.Class / main
java.lang.Class / main
Stop:main
Thread Example#4
Multi threading log messages printed in the file.
§
Create model class. (file name: LogBuildClass.java)
import java.util.HashMap;
import java.util.Map;
public class LogBuildClass {
public static Map logData=new HashMap();
public static void addLogData(String
client, String logInfo){
System.out.println(client);
if(logData.get(client)!=null){
logData.put(client, logData.get(client)+logInfo);
}else{
logData.put(client,
logInfo);
}
}
public static void
addLogData(String logInfo) {
System.out.println(Thread.currentThread().getName());
if (logData.get(Thread.currentThread().getName())
!= null) {
logData.put(Thread.currentThread().getName(),
logData.get(Thread.currentThread().getName())
+ logInfo);
} else {
logData.put(Thread.currentThread().getName(),
logInfo);
}
}
}
§
Create service class. (file name: LogServiceClass.java)
import java.util.Date;
public class LogServiceClass {
public void
serviceLog(String clientName){
for (int i = 1; i <=
5; i++) {
LogBuildClass.addLogData(clientName,
new Date()
+ " : INFO : (" + clientName
+ ")log
message" + i + "\n");
if(clientName.equals("Thread-0")){
try{
Thread.sleep(500);
}catch(Exception e){}
}
if(clientName.equals("Thread-1")){
try{
Thread.sleep(200);
}catch(Exception e){}
}
}
LogWriteFileLogData
wf=new LogWriteFileLogData();
wf.writeFile(clientName);
}
public void serviceLog(){
String
clientName=Thread.currentThread().getName();
for (int i = 1; i <=
5; i++) {
LogBuildClass.addLogData(new Date()
+ " : INFO : (" + clientName
+ ")log
message" + i + "\n");
if(clientName.equals("Thread-0")){
try{
Thread.sleep(500);
}catch(Exception e){}
}
if(clientName.equals("Thread-1")){
try{
Thread.sleep(200);
}catch(Exception e){}
}
}
LogWriteFileLogData
wf=new LogWriteFileLogData();
wf.writeFile();
}
}
§
Create file writer service class. (file name: LogWriteFileLogData.java)
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class LogWriteFileLogData {
public void
writeFile(String client) {
BufferedOutputStream
bos = null;
try {
String
fileName = "E://SLAAWorkspace//Test//src
//pack//thread//logFileData.txt";
String logInfo
= LogBuildClass.logData.get(client);
File file = new File(fileName);
synchronized (file) {
bos = new
BufferedOutputStream(
new FileOutputStream(file,true));
bos.write(logInfo.getBytes());
}
} catch (Exception e) {
System.out.println("---file
exception--");
e.printStackTrace();
} finally {
try {
bos.close();
} catch (Exception e) {
}
}
}
public void writeFile() {
BufferedOutputStream
bos = null;
try {
String
fileName = "E://SLAAWorkspace//Test//src
//pack//thread//logFileData.txt";
String logInfo
= LogBuildClass.logData.get(
Thread.currentThread().getName());
File file = new File(fileName);
synchronized (file) {
bos = new
BufferedOutputStream(
new FileOutputStream(file,true));
bos.write(logInfo.getBytes());
}
} catch (Exception e) {
System.out.println("---file
exception--");
e.printStackTrace();
} finally {
try {
bos.close();
} catch (Exception e) {
}
}
}
}
§
Create Thread class (file name: LogClientThread1.java)
public class LogClientThread1 extends Thread{
public void run() {
LogServiceClass
serv=new LogServiceClass();
serv.serviceLog();
}
}
§
Create another Thread class (file name: LogClientThread2.java)
public class LogClientThread2 extends Thread{
public void run() {
LogServiceClass
serv=new LogServiceClass();
serv.serviceLog();
}
}
§
Create main method class (file name: LogThreadMain.java)
public class LogThreadMain {
public static void main(String[]
args) {
LogClientThread1
cl1=new LogClientThread1();
LogClientThread2
cl2=new LogClientThread2();
cl1.start();
cl2.start();
}
}
§
Run and see output (file name: logFileData.txt)
Fri
Aug 31 15:31:47 IST 2012 : INFO :
(Thread-1)log message1
Fri
Aug 31 15:31:47 IST 2012 : INFO :
(Thread-1)log message2
Fri
Aug 31 15:31:47 IST 2012 : INFO :
(Thread-1)log message3
Fri
Aug 31 15:31:48 IST 2012 : INFO :
(Thread-1)log message4
Fri
Aug 31 15:31:48 IST 2012 : INFO : (Thread-1)log
message5
Fri
Aug 31 15:31:47 IST 2012 : INFO :
(Thread-0)log message1
Fri
Aug 31 15:31:47 IST 2012 : INFO :
(Thread-0)log message2
Fri
Aug 31 15:31:48 IST 2012 : INFO :
(Thread-0)log message3
Fri
Aug 31 15:31:48 IST 2012 : INFO :
(Thread-0)log message4
Fri Aug
31 15:31:49 IST 2012 : INFO : (Thread-0)log message5
Note: absolute path file name E://SLAAWorkspace//Test//src//pack//thread//logFileData.txt
No comments:
Post a Comment