GENERATING PRIME AND FIBONACCI NUMBERS USING MULTITHREADING - JAVA LAB PROGRAM
Aim: To write a multithreaded java program to print both the prime and Fibonacci numbers Algorithm:
Program import java.io.*; import java.util.*; class MyThread1 extends Thread { private PipedReader pr; private PipedWriter pw; MyThread1(PipedReader pr, pipedWriter pw) { this.pr = pr; this.pw = pw; } public void run() { try { int I; for (i=1;i<10;i++) { int j; for (j=2; j<i; j++) { int n = i%j; if (n==0) { break; } } if(I ==j) { pw.write(i+"\n"); } } pw.close(); } catch (IOException e) { } } } class MyThread2 extends Thread { private PipedReader pr; Private PipedWriter pw; MyThread2(PipedReader pr, PipedWriter pw) { this.pr; this.pw=pw; } public void run() { try { int f1,f2=1,f3=1; for(int i=1;i<10;i++) { pw.write(f3+"\n"); f1=f2; f2=f3; f3=f1+f2; } catch (IOException e) { } } } class MultithreadedProgram { public static void main(string[] args)throws Exception { ArrayList list1=new ArrayList list(); ArrayList list list2=new ArrayList list(); PipedWriter pw1=new PipedWriter(); PipedReader pr1=new PipedReader(pw1); MyThread1 mt1=new MyThread1(pr1,pw1); System.out.println("Prime Numbers"); mt1.start(); int item1; while((item1=pr1.read())!=-1) { char ch1=((char)item1); System.out.print(Character.toString(ch1)); list1.add(Character.toString(ch1)); } pr1.close(); PipedWriter pw2=new pipedWriter(); PipedReader pr2=new PipedReader(pw2); MyThread2 mt2=new MyThread2(pr2,pw2); System.out.println("Fibonacci Series"); mt2.satrt(); int item2; while ((item2=pr2.read())!=-1) { char ch2=((char)item2); System.out.print(Character.toString(ch2)); list2.add(Character.toString(ch2)); } pr2.close(); System.out.println("Elements common to both lists are:"); list1.retainAll(list2); for(int i=0;i<list1.size();i++) { System.out.print(list1.get(i)); } } } Output
Conclusion: Thus the java program to print both the prime and Fibonacci numbers was developed and executed successfully. |
No comments:
Post a Comment