Java Thread Programming 1.3-Creating and Starting a Thread

Source: Internet
Author: User
Thread. currentThread ()Public static native Thread currentThread () to determine which thread is executing a segment of code execution of the methods in Thread are listed with some of the following modifiers: native, final, static, and synchronized. as a quick review, native methods are implemented in non-Java code (typically C or C ++ in the JDK ). methods declared to be final may not be overridden in a subclass. when a method is static, it does not pertain to a special instance of the class, but operates at the class level. the f3 synchronized modifier guarantees that no more than one thread is allowed to execute the statements inside a method at one time. later in this book, the synchronized modifier is explained in detail. many methods in the Thread class have the following modifiers: native: methods are implemented using non-java code, such as c, c ++ final: Methods declared as final cannot overwrite static in the quilt class: this method is not called by class instances. You can call synchronized with the Class Name: ensure that only one thread can execute this method at a time. for example, ** Created on 2005-7-6 ** TODO To change the template for this generated file go to * Window-Preferences-Java-Code Style -Code Templates */package org. tju. msnrl. jonathan. thread. chapter1; /*** @ author Administrator ** TODO To change the template for this generated type comment go to * Window-Preferences-Java-Code Style-Code Templates */public class CurrentThread extends Thread {private Thread createThread; public CurrentThread () {this. createThread = Thread. currentThread () ;}public void run () {for (int I = 0; I <10; I ++) this. printMsg ();} public void printMsg () {Thread t = Thread. currentThread (); if (t = this. createThread) {System. out. println ("create thread");} else if (t = this) {System. out. println ("currect thread");} else {System. out. println ("mystery thread") ;}} public static void main (String [] args) {CurrentThread ct = new CurrentThread (); ct. start (); for (int I = 0; I <10; I ++) ct. printMsg () ;}} output: create threadcreate threadcurrect thread GetName ()/setName ()/*
* Created on 2005-7-6
*
* TODO To change the template for this generated file go
* Window-Preferences-Java-Code Style-Code Templates
*/Package org. tju. msnrl. jonathan. thread. chapter1;

/**
* @ Author Administrator
*
* TODO To change the template for this generated type comment go
* Window-Preferences-Java-Code Style-Code Templates */public class GetSetThreadName extends Thread {public void run (){
For (int I = 0; I <10; I ++)
This. printMsg ();
} Public void printMsg (){
Thread t = Thread. currentThread ();
String threadName = t. getName ();
System. out. println ("name =" + threadName );
}
 
Public static void main (String [] args ){
GetSetThreadName maid = new GetSetThreadName ();
GSTN. setname ("getsetthreadname ");
Ststn. Start ();
For (INT I = 0; I <10; I ++)
Stststn. printmsg ();
}
}

Output result:

Name = Main
Name = Main
Name = Main
Name = Main
Name = Main
Name = Main
Name = Main
Name = Main
Name = Main
Name = Main
Name = getsetthreadname
Name = getsetthreadname
Name = getsetthreadname
Name = getsetthreadname
Name = getsetthreadname
Name = getsetthreadname
Name = getsetthreadname
Name = getsetthreadname
Name = GetSetThreadName
Name = GetSetThreadNameThreads Started by the JavaVM
JDK 1.2:

Main/Finalizer/Reference Handler/Signal dispatcher/AWT-Windows/AWT-EventQueue-0/SunToolkit. postEventQueue-0/Screen UpdaterJava Virtual Machine jdk1.2 created thread names are: main, Finalizer, Reference Handler, Signal dispatcher, AWT-Windows, AWT-EventQueue-0, SunToolkit. postEventQueue-0, Screen UpdaterNote that the Reference Handler, Signal dispatcher, and SunToolkit. postEventQueue-0 threads are new to JDK 1.2. the threads named main and Finalizer (Reference Handler and Signal dispatcher for JDK 1.2) are started automatically for every application. the remaining threads are also started by the JavaVM when the application contains any graphical components from AWT or Swing. therefore, in a JDK 1.2 application with a graphical user interface (GUI), eight threads are automatically started by the JavaVM. among them: main and Finalizer (Reference Handler and Signal dispatcher will be automatically created for every application after jdk1.2. If the application involves the image component AWT/Swing, all eight threads will create As mentioned previusly, the main thread is responsible for starting application execution by invoking the main () method. this is the thread from which most other developer-defined threads are spawned by application code. the Finalizer thread is used by the JavaVM to execute the finalize () method of objects just before they are garbage collected. the AWT-EventQueue-0 thread is more commonly known asEventThread and invokes event-handling methods such as actionreceivmed (), keyPressed (), mouseClicked (), and windowClosing (). The functions of each thread are as follows:
Main: main thread of the application
Finalizer: the Java virtual machine executes the finalize () method for garbage collection.
AWT-EventQueue-0: Event thread, calling the message corresponding function Although Java requires none of the following, it's good practice to follow these conventions when naming threads:
1. Invoke setName () on the Thread before start (), and do not rename the Thread after it is started
2. Give each thread a brief, meaningful name when possible.
3. Give each thread a unique name.
4. Do not change the names of JavaVM threads, such as main. recommended use of the setName () function:
1. Called before thread start ()
2. Give the thread a name as concise and clear as possible
3. The thread name is unique.
4. Do not change the thread name created by the Java Virtual Machine, such as the eight
Thread Constructors
The core constructor is as follows: the relationship between public Thread (ThreadGroup group, Runnable target, String name) and ThreadGroup/Thread is like the relationship between folders and files. Folders can contain folders and files, threadGroup can contain both ThreadGroup and Thread
Target indicates the class name that implements the Runnable interface as the thread name.

Start () and isAlive ()  Public native synchronized void start () throws IllegalThreadStateException If the Thread has already been started, an IllegalThreadStateException will be thrown. when the start () method of a Thread is invoked, the new thread is considered to come alive. the thread remains alive until the run () method returns or until the thread is abruptly StoppedBy the stop () method (which is a deprecated method, as of JDK 1.2 !). The start () function must capture the IllegalThreadStateException because if a thread already exists and start () is called again, the public final native boolean isAlive () exception is thrown () can be used on Thread to test whether a thread has been started and is still running isAlive () determine whether the thread is starting or running/** Created on 2005-7-6 ** TODO To change the template for this generated file go to * Window-Preferences-Java-Code Style-Code Templates * /package org. tju. msnrl. jonathan. thread. chapter1; /*** @ author Administrator ** TODO To change the template for this generated type comment go to * Window-Preferences-Java-Code Style-Code Templates */public class IsAlive extends Thread {public void run () {for (int I = 0; I <10; I ++) this. printMsg ();} public void printMsg () {Thread t = Thread. currentThread (); String tName = t. getName (); System. out. println ("name =" + tName);} public static void main (String [] args) {IsAlive ia = new IsAlive (); ia. setName ("IsNameTester"); System. out. println ("before start isAlive:" + ia. isAlive (); ia. start (); System. out. println ("in runing isAlive:" + ia. isAlive (); for (int I = 0; I <10; I ++) ia. printMsg (); System. out. println ("at end of main isAlive:" + ia. isAlive () ;}} output result: before start isAlive: falsein runing isAlive: truename = mainname = mainat end of main isAlive: truename = IsNameTestername = IsNameTester Thread. sleep ()  Sleeping is a much better option than using a busy loop. A sleeping thread does not use any processor cycles because its execution is suincluded for the specified duration. use sleep instead of a true loop. sleep suspends a thread for a certain period of time. The try/catch construct is necessary because while a thread is sleeping, it might be InterruptedBy another thread. one thread might want to interrupt another to let it know that it shoshould take some sort of action. later chapters further lead e the use of interrupts. here, it suffices to say that a sleeping thread MightBe interrupted and will throw an InterruptedException if this occurs. an InterruptedException exception must be caught when using sleep, because when the process is sleep, it may be interrupted by other processes.  /** Created on 2005-7-6 ** todo to change the template for this generated file go to * window-preferences-Java-code style-code templates */package Org. tju. msnrl. jonathan. thread. chapter1; /*** @ author administrator ** todo to change the template for this generated type comment go to * window-preferences-Java-code style-code templates */public class sleep extends thread {public void run () {This. loop ();} public void loop () {thread t = thread. currentthread (); string name = T. getname (); system. out. println ("just enter loop" + name); For (INT I = 0; I <10; I ++) {try {thread. sleep (200);} catch (interruptedexception e) {// This exception must be caught} system. out. println ("name =" + name);} system. out. println ("be about to leave loop" + name);} public static void main (string [] ARGs) {sleep s = new sleep (); S. setname ("sleeptester"); S. start (); try {thread. sleep (700);} catch (interruptedexception e) {} s. loop () ;}} output result: just enter loop sleeptestername = shortenter loop mainname = Signature = mainname = sleeptestername = mainname = External about to leave loopsleeptestername = mainname = mainbe about to leave loopmain

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.