==
package Demo6;
/**
* Title -- Advanced Java_ Multi-threading Part 4 -- Multiple Locks; Using Synchronized Code Blocks
* Note:--
* @author Dharmaraj.Net
*/
public class App {
public static void main(String[] args) {
new Worker().main();
}
}
===
package Demo6;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Worker {
private List<Integer> list1 = new ArrayList<Integer>();
private List<Integer> list2 = new ArrayList<Integer>();
private Object lock1 = new Object();
private Object lock2 = new Object();
private Random random = new Random();
public void main() {
System.out.println("Starting.....");
long start = System.currentTimeMillis();
// process();
Thread t1 = new Thread(new Runnable() {
public void run() {
process();
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
process();
}
});
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Time taken..." + (end - start));
System.out.println("Liat 1" + list1.size());
System.out.println("Liat 1" + list2.size());
}
public void stageOne() {
synchronized (lock1) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list1.add(random.nextInt(100));
}
}
public void stageTwo() {
synchronized (lock2) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list2.add(random.nextInt(100));
}
}
public void process() {
for (int i = 0; i < 1000; i++) {
stageOne();
stageTwo();
}
}
}
===
No comments:
Post a Comment