Java Basics _ Multithreading 2[Threading Control]

Source: Internet
Author: User
Tags thread class


Multithreading 2[Threading Control]

1. Thread scheduling and setting thread priority

(1). Two models of thread scheduling
A: Time-sharing scheduling model All threads take turns using the CPU's right of use, evenly allocating each thread to occupy the CPU of the chip.

B: Preemptive scheduling model prioritize the use of high-priority threads using the CPU, if the priority is the same, then this time will randomly select a high priority thread to get the CPU
A bit more time slices.
Java uses a preemptive scheduling model.

(2). Priority of Threads
A: Gets the priority of the thread
Public final int getpriority (): Returns the priority of the thread
Default is 5

B: Set the priority of the thread
Public final int setpriority (int i): Sets the priority of the thread
The value of the thread's priority range is: 1-10

Exception: java.lang.IllegalArgumentException: Illegal parameter exception, indicating that an incorrect parameter value was passed to the method

C: Precautions
The high priority of a thread simply means that the probability of acquiring the CPU's time slice is high, because there is randomness, only in the case of multiple tests can see the effect.

(3). Code implementation
Thread class
public class MyThread extends thread{
@Override
public void Run () {
Super.run ();
for (int i = 0; i <; i++) {
System.out.println (GetName () + "---" +i);
}
}
Test class
public class ThreadTest {
public static void Main (string[] args) {
MyThread Mt =new MyThread ();
MyThread MT1 =new MyThread ();
Mt.setname ("Big Pig");
Mt1.setname ("Piglet");
Set Thread Priority
Mt.setpriority (10);
Mt1.setpriority (1);
Get the default priority level
System.out.println (Mt.getpriority ());
System.out.println (Mt1.getpriority ());
Mt.start ();
Mt1.start ();
}
}

2. Thread-controlled sleep thread

(1). method
public static void sleep (long millis);//thread sleep time for the current thread to "pause for a period of time" in the specified millisecond.

(2). Code implementation
Thread class
public class MyThread extends thread{
@Override
public void Run () {
Super.run ();
for (int i = 0; i <; i++) {
System.out.println (GetName () + "---" +i+ ", The time is:" +new date ());
Sleep
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}

}
}
}
Test class
public class ThreadTest {
public static void Main (string[] args) {
MyThread Mt =new MyThread ();
MyThread MT1 =new MyThread ();
MyThread mt2 =new MyThread ();
Mt.setname ("Big Pig");
Mt1.setname ("Piglet");
Mt2.setname ("Fat pig");
Mt.start ();
Mt1.start ();
Mt2.start ();
}
}


3. Thread-controlled join thread

(1). When to use the join thread
When there is a sequencing, you can consider using the join thread. That is, one of the threads is gone, the other thread can go to grab the CPU right, this situation can be used.

(2). Join Threading Method
Public final void Join ()
Throws Interruptedexception: Waiting for the thread to terminate


(3). Code implementation
Thread class
public class MyThread extends thread{
@Override
public void Run () {
Super.run ();
for (int i = 0; i <; i++) {
System.out.println (GetName () + "---" +i);
}
}
}
Test class
public class ThreadTest {
public static void Main (string[] args) {
MyThread Mt =new MyThread ();
MyThread MT1 =new MyThread ();
MyThread mt2 =new MyThread ();
Mt.setname ("Big Pig");
Mt1.setname ("Piglet");
Mt2.setname ("Fat pig");

Mt.start ();
try {
Mt.join ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
Mt1.start ();
Mt2.start ();
}
}
Results
The big Pig executes first, then the piggy and the Fat pig go to grab the CPU use


4. Thread Control of comity threads

(1). Comity Threading Method
public static void Yield (): Pauses the executing thread object and executes other threads.


(2). comity Thread Usage conditions
Let the thread maintain a certain degree of harmony, that is to say a thread executes, B thread executes, then a, then B ...., this one will only play a part (one person at a time).

(3). Code implementation
//thread class
public class MyThread extends thread{
@Override
public void Run () {
//super.run ();
for (int i = 0; i < i++) {
System.out.println (getName () + "---" +i);
Set the comity thread
Thread.yield ();
}
}
}
//test class
public class ThreadTest {
public static void Main (string[] args) {
MyThread mt =new MyThread ();
MyThread mt1 =new MyThread ();
MyThread mt2 =new MyThread ();
Mt.setname ("Big Pig");
Mt1.setname ("Piglet");
Mt2.setname ("Fat pig");

Mt.start ();
Mt1.start ();
Mt2.start ();
}
}


5. Background Threads

(1). Background Threading Method
public static void Setdaemon (Boolean on): The thread is marked as a daemon thread or a user group thread, and the Java virtual machine exits when a running thread is a daemon thread
Note: This method must be called before the thread is started.

(2). Code implementation
Thread class
public class MyThread extends thread{
@Override
public void Run () {
Super.run ();
for (int i = 0; i <; i++) {
System.out.println (GetName () + "---" +i);
}
}
}
Test class
public class ThreadTest {
public static void Main (string[] args) {
Other Threads Execute content
MyThread Mt =new MyThread ();
MyThread MT1 =new MyThread ();
Mt.setname ("Guan Yu");
Mt1.setname ("Zhang Fei");
Flag as daemon thread (daemon main threads)
Mt.setdaemon (TRUE);
Mt1.setdaemon (TRUE);

Mt.start ();
Mt1.start ();

Main thread Execution content
Thread.CurrentThread (). SetName ("Liu Bei");
for (int i=0;i<5;i++) {
System.out.println (Thread.CurrentThread (). GetName () + "----" +i);
}
}
}
The main thread of the daemon, when the for () loop executes to 4, the other two threads will stop


6. Thread-controlled disconnection process

(1). Middle Thread Break
Public final void Stop (): Ends a thread (obsolete, but still available), has no security, exits directly, and does not execute subsequent code.
public void interrupt (); ends a thread and continues execution of subsequent code by throwing an exception.


(2). Code implementation
Thread class
public class MyThread extends thread{
@Override
public void Run () {
Super.run ();
System.out.println ("Start" +new Date ());
Rest for 10 seconds.
try {
Thread.Sleep (10000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
System.out.println ("Rest 10 seconds");
}

System.out.println ("End" +new Date ());
}
}
Test class
public class ThreadTest {
public static void Main (string[] args) {
Other Threads Execute content
MyThread Mt =new MyThread ();
Mt.setname ("three fat");
Mt.start ();
More than three seconds without executing code, then end this one thread
try {
Thread.Sleep (3000);
Mt.stop ();
Mt.interrupt ();
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Use the Stop () method to output the result:
Start Sat Sep 00:04:27 CST 2018
Use the interrupt () method to output the results
Start Sat Sep 00:04:27 CST 2018
Rest for 10 seconds.
End Sat Sep 00:04:30 CST 2018



7. Thread Life cycle

Java Basics _ Multithreading 2[Threading Control]

Related Article

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.