Java threads (1)

Source: Internet
Author: User

Java threads (1)

1. Process and thread

Multi-process:

Multiple tasks (programs) can be run in the operating system at the same time)

Multithreading:

Multiple sequential streams (at the same time) are executed in the same application.

2. multi-threaded program running mode


3. Define the thread method


Method 1:

Defines a Thread class, which inherits the class Thread and overwrites the method run (). The method run () is called the Thread body;

Because Java only supports single inheritance, classes defined using this method cannot inherit other classes.


Class FirstThread extends Thread {public void run () {for (int I = 0; I <100; I ++) {System. out. println ("FirstThread -->" + I );}}}
Note: This program has three threads.
1. The main function is a thread.
2. the ft thread object is the second thread after startup
3. Garbage collection mechanism thread
Class Test {public static void main (String args []) {// the object that generates the Thread class FirstThread ft = new FirstThread (); // start the thread ft. start ();}}
Test. Add a for loop to the Test class.

Class Test {public static void main (String args []) {// the object that generates the Thread class FirstThread ft = new FirstThread (); // start the thread (start () is required ()) ft. start (); for (int I = 0; I <100; I ++) {System. out. println ("main -->" + I );}}}
After running, two loops are found to run alternately, indicating that the two loops are in different threads.


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.