The main method in Java is actually a thread, which is called the main path.
Q: Since the main method appears as a thread, how many threads are there at least in Java?
Answer: There are at least two threads. Each time you start Java, the JVM is actually started, then the garbage collection mechanism is a thread, there are altogether two threads, the main thread and the GC.
Determines whether a thread can start using the. IsAlive method and returns a Boolean value.
Forced execution of Threads
In the course of a thread, you can use the join () method to force the threads to run, the other threads cannot run while the thread is forced to run, and must wait until the thread has finished running to execute.
The sleep of a thread
The program can implement the thread transient hibernation, directly using Thread.Sleep ();
Termination of the thread
You can implement a thread termination, using the interrupt method.
Background thread
In Java, as long as a thread in the foreground is running, the entire Java process does not disappear, so a background thread can be set at this point, and if the Java process is finished, the thread will not disappear.
You can use the Setdaemon () method.
Priority of the thread
In a Java thread, which thread has the highest priority is the first thread to execute.
The priority categories are as follows:
Special: In main thread main, the default priority is norm_priority, that is, the primary thread has a medium priority.
Comity of Threads
In the use of threads, the yield () method can be used to implement thread comity, that is, temporarily suspend the current thread for other threads to execute.
Cases:
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<5;i++) {try{ Thread.Sleep (500);} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "run, I =" + i);//Gets the name of the current thread if (i==2) { System.out.print ("Thread comity:"); Thread.CurrentThread (). yield ();//Thread Comity}}}};p ublic class Threadyielddemo{public static void Main (String args[]) { MyThread my = new MyThread ();//Instantiate MyThread object thread t1 = new Thread (My, "thread A"); Thread t2 = new Thread (my, "thread B"); T1.start (); T2.start ();}};
Summary: This article mainly learn the Java thread in the sleep, termination, comity and other functions, in fact, is a basic operation of threads.
Java Notes: Understanding and Application of multithreading (II.)