In: Computer Science
DO THIS IN JAVA
Write a complete Java program. the program has two threads. One thread prints all capital letters 'A' to'Z'. The other thread prints all odd numbers from 1 to 21.
/*
* The java program that create two instances of Thread classes and
calls start methods to print the capital letters from A to Z and
odd numbers from
* 1 to 21.
* */
//ThreadMain.java
public class ThreadMain
{
public static void main(String[] args)
{
System.out.println("Printing
capital letters and odd numbers using two threads");
/*Create an instance of Thread
classes*/
Thread thread1=new Thread(new
CapitalLetters());
Thread thread2=new Thread(new
OddNumbers());
//call start methods on thread1 and
thread2
thread1.start();
thread2.start();
}
//inner static class to print capital letters A to
Z
static class CapitalLetters implements Runnable
{
public synchronized void
run()
{
/*synchronized
run method to print the capital letters
* from A to
Z*/
for(char
ch='A';ch<='Z';ch++)
{
System.out.println(ch);
}
}
}
//inner static class to print odd numbers from 1 to
21
static class OddNumbers implements Runnable
{
/*synchronized run method to print
the odd numbers
* from 1 to 21*/
public synchronized void
run()
{
for(int
i=1;i<=21;i++)
{
if(i%2==1)
System.out.println(i);
}
}
} //end of inner class ,OddNumbers
}//end of the class
-------------------------------------------------------------------------------------------
Sample Output:
Printing capital letters and odd numbers using two
threads
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
1
3
5
7
9
11
13
15
17
19
21