About
import java.util.ArrayList; import java.util.Arrays; import java.util.List;
public class Code implements Runnable{ private List<Integer> list1; private List<Integer> list2; private List<Integer> result = new ArrayList<>(); private List<Integer> odd = new ArrayList<>(); public Code(List<Integer> list1, List<Integer> list2) { this.list1 = list1; this.list2 = list2; } public synchronized void Union() { for (int i = 0; i < list1.size(); i++) { result.add(list1.get(i)); } for (int i = 0; i < list2.size(); i++) { result.add(list2.get(i)); }
}
public List<Integer> getOdd() {
return odd;
}
public synchronized void Odd() {
for (int i = 0; i < list1.size(); i++) {
if(list1.get(i)%2 == 1) {
odd.add(list1.get(i));
}
}
for (int i = 0; i < list2.size(); i++) {
if(list2.get(i)%2 == 1) {
odd.add(list2.get(i));
}
}
}
public List<Integer> getResult() {
return result;
}
public void run() {
if(Thread.currentThread().getName().equals("union")) {
Union();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(Thread.currentThread().getName().equals("odd")) {
Odd();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
list1.addAll(Arrays.asList(0,1,2));
list1.addAll(Arrays.asList(5,3,7));
Code result = new Code(list1,list2);
Thread thread1 = new Thread(result,"union");
Thread thread2 = new Thread(result,"odd");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Union is :"+result.getResult());
System.out.println("Odd is "+result.getOdd());
}
}