import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadPoolExample1 {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
Employee first= new Employee();
Employee first1 =first.get();
first.setName("abishkar");
first.setSalary(100);
Employee seccond= new Employee();
Employee seccond1= seccond.get();
first.setName("BillGates");
first.setSalary(10);
List<Future<Employee>> results = executor.invokeAll(asList(new MyThread1(first1), new MyThread1(first1)));
executor.shutdown();
for (Future<Employee> result : results) {
System.out.println("Result: " + result.get());
}
}
}
class MyThread1 implements Callable<Employee> {
Employee object;
String name="";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
MyThread1(Employee object) {
this.object = object;
}
@Override
public Employee call() throws Exception {
System.out.println(object.getName()+ object.getSalary());
object.setName("BillGates");
object.setSalary(10);
System.out.println(object.getName()+ object.getSalary());
setName(object.getName());
System.out.println(getName());
// }
return new Employee();
}
}
class MyThread2 implements Callable<Object> {
@Override
public Object call() throws Exception {
for (int j = 100; j < 110; j++) {
System.out.println("j = " + j);
Thread.sleep(500);
}
return new Object();
}
}
class Employee {
private String name;
private int salary;
Employee() {
this.name = "abishkar";
this.salary = 100;
}
Employee(int i) {
this.name = "BillGates ";
this.salary = 10;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the salary
*/
public int getSalary() {
return salary;
}
/**
* @param salary the salary to set
*/
public void setSalary(int salary) {
this.salary = salary;
}
private static ThreadLocal threadLocal = new ThreadLocal(){
@Override
protected Employee initialValue() {
return new Employee();
}
};
public static Employee get() {
return (Employee) threadLocal.get();
}
}
No comments:
Post a Comment