Java Thread creation and startup (i) __java

Source: Internet
Author: User
Tags thread class


Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses. The function of each thread is to accomplish a certain task, which is to execute a program flow (a sequence of code execution). Java uses the thread execution body to represent this stream of programs.


public class Firstthread extends Thread {

	private int i;

	@Override
	//Rewrite the Run method, the method body of the Run method is the thread execution body public
	void Run () {

		System.out.println ("Hello," +getname () + "" + i);
	}
	
	public static void Main (string[] args) throws exception{
		for (int i = 0; i < i++) {
			
			//Invoke thread's Currentthre The ad () method gets the current thread
			System.out.println (Thread.CurrentThread (). GetName () + "" + i);
			
			if (i==2) {
				//Create and start the first thread
				new Firstthread (). Start ();
				
				Create and start the second thread
				new Firstthread (). Start ();
	
	


The Firstthread class in the above program inherits the thread class and implements the Run method, the code execution flow in the Run method is the task that the thread needs to complete. Although the above program only shows the creation and launch of 2 threads, in fact the program has 3 threads, that is, the program shows the 2 child threads and the main thread created. When a Java program begins to run, the program creates at least one main thread, and the threads of the main process are determined by the main method.


When you create a thread class by using methods that inherit from the thread class, the instance variables of the thread class cannot be shared among multiple 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.