Java Thread Processing II

Source: Internet
Author: User

To write a printer class

Write a two-way

1  Public classPrinter {2 3      Public voidprint1 ()4     {5         6System.out.print ("Micro");7System.out.print ("Cold");8System.out.print ("the");9System.out.print ("Rain");Ten System.out.println (); One     } A      Public voidPrint2 () -     { -          theSystem.out.print ("Good"); -System.out.print ("People"); - System.out.println (); -          +          -     } +}

Purpose: To enable two threads to execute two methods in this class

Line Cheng:

 Public class extends Thread {    publicstatic  Printer p1; @Overridepublicvoid run () {    for (int i = 1; I <=500; i++) {        p1.print1 ();}    } 

Thread Two:

 Public class Implements runnable{    publicstatic  Printer p2;    @Override    publicvoid  run () {       for (int i = 1; I <=500; i++) {            p2.print2 ();     }}}

Method calls in the test class

 Public class Test {publicstaticvoid  main (string[] args) {    Printer p=New  Printer ();    MyThread T1=new  MyThread ();    T1.p1=p;    T1.start ();    MyThread2 t2=new  MyThread2 ();    T2.P2=p;    thread T3=new  thread (T2);    T3.start ();    }}

The following occurs: Because the programmer cannot manually intervene the CPU to allocate thread resources

Workaround: Add a sync lock so that when one thread finishes executing, another thread has the right to execute

 Public classPrinter { Public voidprint1 () {synchronized( This) {System.out.print (Micro); System.out.print (Cold); System.out.print (Of); System.out.print (Rain);        System.out.println (); }            }     Public voidPrint2 () {synchronized( This) {System.out.print (Good); System.out.print (People);        System.out.println (); }            }}

Resolved!!!!!!!!!

Java Thread Processing II

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.