A good memory is better than a bad pen. 77-Multithreaded-thread the thread object of a subclass is different

Source: Internet
Author: User

thread objects are different for threads subclasses.
Like what:
Easyselfthread thread = new Easyselfthread ();
Same Thread Object
thread T1 = new Thread (thread, "T1");
Thread t2 = new Thread (thread, "==t2");//(3)
Because T1 and T2 are two objects, the threads they start can access the run () function at the same time.

thread object for threads sub-class is different Java source code
Package com.thread;

/**
* Thread objects generated by subclasses of thread, are threads of different objects
*
* @author Fan Fangming
*/

 Public  class easyselfthread implements Runnable {    //public synchronized void print () {//(1)     Public  void Print() {//(1)         for(inti =0; I <3; i++) {System.out.println (Thread.CurrentThread (). GetName () +" : "+ i);Try{Thread.Sleep ( -); }Catch(Exception e)            {E.printstacktrace (); }        }    } Public   void Run() { This. print (); } Public Static void Main(string[] args) {Easyselfthread thread =NewEasyselfthread ();//Same Thread objectThread T1 =NewThread (thread,"T1"); Thread t2 =NewThread (thread,"==t2");//(3)T1.start ();    T2.start (); }}

Run Results
t1:0
==t2:0
==t2:1
T1:1
==t2:2
T1:2

You can also modify the Run method with synchronized, but they are still two objects, not one.

A good memory is better than a bad pen. 77-Multithreaded-thread the thread object of a subclass is different

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.