Two ways to implement java-based threading

Source: Internet
Author: User
Tags thread class

Process refers to an in-memory running application, each process has its own separate piece of memory space, a process can start multiple threads! Threads are always part of a thread, and threads in a process share the memory of the process

note: for java, The run () method has nothing special. Like the main () method, it is just a new thread that knows the method name (and Signature) of the Call. therefore, It is legal to raise the Run method on runnable or Thread. But does not start a new thread, start a new thread to call the start () method

There are two ways to implement threads in Java: 1. inherit the thread class

 packageunit_fifteen; public classTestthreadextendsThread {PrivateString name;  publictestthread (String Name) { this. Name =name; } @Override public voidRun () { for(inti = 0; I < 5; i++) {             for(intj = 0; J < 2; J + +) {System.out.println (name+ ":" +i); }        }    }    //inherit the thread class     public Static voidmain (string[] Args) {//You can create a thread without a nameTestthread tone =NewTestthread ("ah san"); Testthread Ttwo=NewTestthread ("john doe");        Tone.start ();    Ttwo.start (); }} 

2. Implement runnable interface

 packageunit_fifteen; public classTestrunnnableImplementsRunnable { public Static voidmain (string[] Args) {//Implement the Runnable interface, you can create a thread that is not namedTestrunnnable Dsone =NewTestrunnnable ("ah san"); Testrunnnable Dstwo=NewTestrunnnable ("john doe"); //creates a thread object as a parameter to an object of a class that implements the Runnable interfaceThread tone =NewThread (dsone); Thread Ttwo=NewThread (dstwo);        Tone.start ();    Ttwo.start (); }    PrivateString name;  publictestrunnnable (String Name) { this. Name =name; } @Override public voidRun () { for(inti = 0; I < 5; i++) {             for(intj = 0; J < 2; J + +) {System.out.println (name+ ":" +i); }        }    }}

Two ways to implement java-based threading

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.