Title One: Write two threads, one thread prints 1~52, another thread prints the letter a~z. The print order is 12a34b56c ..... 5152Z. Requires the use of communication between threads. Package test;
Import Java.lang.Thread;
Class printer{
private int index = 1;
Public synchronized void print (int n) {
while (index%3==0) {
try{
Wait ();
/* The Notify method that calls this object in other threads money, causing the current thread to wait */
}catch (Exception e)
{
E.printstacktrace ();
}
}
System.out.print (index);
index++;
Notifyall ();
}
Public synchronized void print (char c) {
while (index%3!=0) {
try{
Wait ();
}catch (Exception e) {
E.printstacktrace ();
}
}
System.out.print (c);
System.out.print (index);
index++;
Notifyall ();
}
}
Class Numberprinter extends thread{
Private Printer p;
Public Numberprinter (Printer p) {
This.p=p;
}
public void Run () {
for (int i=1;i<=52;i++)
P.print (i);
}
}
Class Charprinter extends thread{
Private Printer p;
Public Charprinter (Printer p) {
This.p=p;
}
public void Run () {
for (char c= ' A '; c<= ' Z '; C + +)
P.print (c);
}
}
public class MyThread {
public static void Main (String args[]) {
Printer p = new Printer ();
Thread T1 = new Numberprinter (p);
Thread t2 = new Charprinter (p);
T1.start ();
T2.start ();
}
}
Practice of multithreading Classic programming problems