A single-task flow in a "thread" Java program. We do this by placing each task in a relatively separate thread. Main is the main thread
Concurrent completes multiple tasks at the same time. Program execution steps are sequential, but many times we need to deal with a problem in parallel instead of dealing with a problem sequentially
"Multithreaded" threads are also considered objects, multithreading refers to multiple thread objects
"Thread-supported classes in the API" Java.lang.Thread. The object of the thread class is the threading object
Practice one, initialize thread objects, print threads
Package Pkg3;public class Test3 implements runnable{ Thread Th1; Public Test3 () {//2 th1=new thread (this);//2-1 initialized Thread Object th1.start ();//2-2 started the thread object and automatically called the Run method } public static void Main (string[] args) { new test3 ();//1. Starting from the main thread, calling construction method } @Overridepublic void Run () { //3// TODO auto-generated Method Stub System.out.println ("thread ran");//3-1 print Thread, "Run"}}
Practice the life cycle of a thread: new, runnable, not runnable, dead
Package Pkg3;public class Test3 implements runnable{ Thread Th1; Public Test3 () {//2 th1=new thread (this);//2-1 initialized Thread Object th1.start ();//2-2 started the thread object and automatically called the Run method } public static void Main (string[] args) { new test3 ();//1. Starting from the main thread, calling construction method } @Overridepublic void Run () { //3// TODO auto-generated Method Stub while (True) { System.out.println ("thread ran"),//3-1 print thread, "run" try { Th1.sleep (500);//Force Sleep 500 MS, enter non-running status not runnable (sleep, jam, queue) } catch (Interruptedexception e) { //TODO Auto-generated Catch block e.printstacktrace ();}}}
Practice three, multithreading
Package Pkg3;public class Test3 implements runnable{ Thread th1,th2; Public Test3 () {//2 th1=new thread (this);//2-1 initializes thread object Th2=new thread (this); Th1.start ();//2-2 initiates a thread object, automatically calls the Run method Th2.start (); } public static void Main (string[] args) { new test3 ();//1. Starting from the main thread, calling construction method } @Overridepublic void Run () { //3// TODO auto-generated Method Stub /*while (True) { System.out.println ("thread ran"),//3-1 print thread, "run" try { Th1.sleep (500);//Forced Sleep 500 ms, enter non-running status not runnable (sleep, jam, queue) } catch (Interruptedexception e) { //TODO auto-generated catch block e.printstacktrace (); } } * /thread th=thread.currentthread ();//This method can be used to determine the thread object that enters the Run method if (th==th1) { System.out.println (" Thread 1 Ran "); } if (th==th2) { System.out.println ("Thread 2 Ran");}}}