Practice of multithreading Classic programming problems

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.