Use threads for batch collection problems

Source: Internet
Author: User

Use threads for batch collection problems

Method 1: Inherit the Thread class
Method 2: implement the runnable interface

The most important method of the thread class is run (), which is called by the START () method of the thread class,
Thread. Join ();

I:
Public class mythread extends thread
{
Int COUNT = 1, number;
Public mythread (INT num)
{
Number = num;
System. Out. println
("Create thread" + number );
}
Public void run (){
While (true ){
System. Out. println
("Thread" + number + ": Count" + count );
If (++ COUNT = 6) return;
}
}
Public static void main (string ARGs [])
{
For (INT I = 0;
I <5; I ++) New mythread (I + 1). Start ();
}
}

Result:
Thread 1: Count 2
Create thread 3
Thread 3: Count 1
Thread 1: Count 3
Thread 1: Count 4
Thread 1: Count 5
Create thread 4
Thread 4: Count 1
Create thread 5
Thread 5: Count 1
Thread 3: Count 2
Thread 3: Count 3
Thread 4: Count 2
Thread 3: Count 4
Thread 4: Count 3
Thread 5: Count 2
Thread 5: Count 3
Thread 5: Count 4
Thread 4: Count 4
Thread 3: Count 5
Thread 4: Count 5
Thread 5: Count 5

Conclusion:Multiple Threads are executed in disorder without affecting each other.
Ii. Use Interfaces
The only difference from the above program is to generate a thread. Add a new thread (); as follows:
New thread (New mythread (I + 1). Start ();

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.