Java BASICS (9)

Source: Internet
Author: User

Java BASICS (9)
I. threads and processes

Process):

1. It is a running activity of a computer program about a dataset. It is the basic unit for the system to allocate and schedule resources and the basis of the operating system structure.

2. In the early process-oriented computer structure, processes are the basic execution entities of programs.

3. In the modern thread-Oriented Computer structure,A process is a thread container.. Programs are descriptions of commands, data, and their organizational forms,Process is the entity of the program.

Thread):

1. It is regarded as the smallest unit in the process.

2. A process can contain one or more threads (that is, a short piece of code ).

3. A thread can also be considered as a lightweight process (for example, one process has only one thread ).

4. Running multiple threads in a single program to complete different jobs at the same time is calledMultithreading.

 

CPU: The execution task is a thread. The thread will be continuously switched on different time slices.

2. Two ways to start a thread: 1. Two ways to start a thread:

1. inherit the ThreadClass

1/** 2 * inherit thread class 3 */4 public class ThreadMusic extends Thread {5 @ Override 6 public void run () {7 synchronized (this) {// synchronize 8 for (int I = 0; I <100; I ++) {9 System. out. println (this. getName () + "------ listen to music ------" + I); 10} 11} 12} 13}

2. Implement RunnableInterface

Difference: If a class inherits other classes, it cannot inherit the Thread class. in Java, a class can only inherit one class, and if a class implements one interface, you can also implement other interfaces, which can be implemented in multiple ways. Therefore, Runable is more scalable.

1/** 2 * implement the runnable interface 3 */4 public class RunnableMusic implements Runnable {5 @ Override 6 public void run () {7 synchronized (this) {// synchronize 8 for (int I = 0; I <100; I ++) {9 System. out. println (Thread. currentThread (). getName () + "------ listen to music ------" + I); 10} 11} 12} 13}
2. Start the thread process:

Method 1: Inherit the Thread class

① Define what needs to be encapsulated into a thread object;

② Custom extends Thread class

③ Override run method: Write ①

④ Create a custom object t

⑤ Start thread t. start ();

Method 2: implement the Runnable interface

① Define what needs to be encapsulated into a thread object;

② Custom class implements Runnable interface

③ Override run method: Write ①

④ Create a custom object t

⑤ Start Thread new Thread (t). start ();

Test thread:

1 public class testThread {2/** 3 * Test threadMusic 4 */5 @ Test 6 public void testThread () {7 ThreadMusic music = new ThreadMusic (); 8 music. start (); 9} 10 11/** 12 * test threadMusic13 */14 @ Test15 public void testRunnable () {16 RunnableMusic runnableMusic = new RunnableMusic (); 17 Thread thread = new Thread (runnableMusic); 18 thread. start (); 19} 20}
3. Thread method 1. Thread class Method

Static void sleep (long millis) slews the currently running thread (paused) within a specified millisecond ).

1/** 2 * test sleep method 3 */4 public class SleepTest {5 public static void main (String [] args) throws InterruptedException {6 for (int I = 1; I <11; I ++) {7 System. out. println (I); 8 Thread. sleep (1000); // sleep for 1 second 9} 10} 11}
2. Get the Thread name
1/** 2 * inherit thread class 3 */4 public class ThreadMusic extends Thread {5 @ Override 6 public void run () {7 synchronized (this) {8 for (int I = 0; I <100; I ++) {9 System. out. println (this. getName () + "------ listen to music ------" + I); // get the Thread name 10} 11} 12} 13}
3. Get the Runnable name
1/** 2 * implement the runnable interface 3 */4 public class RunnableMusic implements Runnable {5 @ Override 6 public void run () {7 synchronized (this) {// synchronize 8 for (int I = 0; I <50; I ++) {9 // get the Runnable name, currentThread () method, returns the currently executing thread reference 10 System. out. println (Thread. currentThread (). getName () + "------ listen to music ------" + I); 11} 12} 13} 14}

Conclusion: The Inheritance and implementation methods for obtaining thread names are different.

4. Thread method (jion)

Void join () method: Wait for the thread to terminate.

1/** 2 * JoinThread Thread 3 */4 public class JoinThread extends Thread {5 @ Override 6 public void run () {7 for (int I = 0; I <100; I ++) {8 System. out. println ("JoinThread --->" + I); 9 try {10 Thread. sleep (1); // JoinThread sleep for another second, in order to appear more regular 11} catch (InterruptedException e) {12 e. printStackTrace (); 13} 14} 15} 16}

Test join method:

1/** 2 * test join method 3 */4 public class JoinDemo {5 public static void main (String [] args) throws InterruptedException {6 JoinThread joinThread = new JoinThread (); 7 joinThread. start (); 8 9 for (int I = 0; I <100; I ++) {10 System. out. println ("main --->" + I); 11 if (I = 10) {12 joinThread. join (); // wait until the Thread is terminated before continuing to execute main Thread 13} 14 Thread. sleep (1); // master thread simulated network latency 15} 16} 17}

Understanding: joinThread. join (): When the main thread is executed to 10, the JionThread thread is added. Wait until all JionThread threads are executed, and then continue to execute the main thread.

In addition to the jion () method, there is also the jion (long millils) method (waiting for a fixed time for thread execution, and then one to one, jion is invalid ).

4. thread priority

The execution of a high-priority thread takes precedence over a lower-priority thread. It is not absolute. A thread with a higher priority may be executed first than a thread with a lower priority, high-priority threads have a higher chance of execution priority;

(For example, if two threads have a high priority and a low priority, the execution of a thread with a high priority is far greater than that of a thread with a low priority if it runs for an hour, but it does not mean that the execution of a thread with a high priority is completed first, in the execution of low priority ).

Method:

Int getPriority () returns the priority of the thread.

Void setPriority () changes the thread priority

1 public class PriorityDemo {2 public static void main (String [] args) {3 Thread thread = Thread. currentThread (); 4 System. out. println (thread. getPriority (); // get priority 5 thread. setPriority (8); // set priority 6 System. out. println (thread. getPriority (); 7} 8}

The default priority of a custom thread is the same as that of the thread that created the environment.

5. daemon thread

Each thread has a priority. The execution of a high-priority thread takes precedence over that of a low-priority thread. Each thread can or cannot be marked as a daemon.

  Background thread: Refers to the thread that provides services for other threads, also knownDaemon thread. The JVM garbage collection thread is a background thread.

Methods provided by the Thread class:

Method: void setDaemon (boolean on) marks the thread as a daemon or user thread.

Method: isDaemon () is used to test whether the thread is a daemon.

1 public class DaemonDemo {2 public static void main (String [] args) {3 // obtain the main Thread 4 thread Thread = Thread. currentThread (); 5 System. out. println (thread. isDaemon (); // false non-Background thread 6 // try to change to background thread 7. setDaemon (true); 8 // The active thread cannot be set as the background thread, and the main thread cannot be set as the background thread. 9 System. out. println (thread. isDaemon (); // Exception in thread "main" java. lang. IllegalThreadStateException10} 11}

Conclusion: The default status of the custom thread is related to the environment. The thread created in the background thread is the background thread by default, and the thread created in the foreground thread is the foreground thread.

6. Thread Synchronization

Three Synchronization Methods in Java:

1. synchronous code block

Synchronized (synchronization listener object ){

Code to be synchronized

}

Note: The synchronization listening object can be any object but accessed by multiple threads. this object must be the same object. Generally, or the bytecode object of the current class (class name. class), or related business objects.

2. synchronous method writing:

Synchronized is directly used as the modifier of the method by means of {} of the method;

3. synchronization mode-lock)

 

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.