Thread:
Benefits of Multithreading: Resolves an issue where multiple task codes are executed concurrently in a process.
Customize how threads are created:
1. Customize a class to inherit the thread class, overriding the thread's Run method. The task code for the custom thread is written in the Run method, creating an object of the thread subclass and calling the start () method to start the thread.
2. Customize a class to implement the Runnable interface, implement the Run method in the Runnable interface, and the custom thread's task code is written inside the run method, creating an object of the Runnable implementation class. Creates a thread object and passes the object of the Runnable implementation class as a parameter, invoking the Start method of the thread object to open the threads.
The root cause of thread safety problems:
Two or more than two threads must exist to share a resource.
The code that operates a shared resource must have two or more sentences
Solutions for thread safety issues:
Synchronous code block resolution
Synchronized (lock) {
Code that needs to be synchronized
}
Same Walk number resolution:
Modifier synchronized function name (formal parameter list ... ){
}
1 Public classDemo1extendsthread{2 3 Publicdemo1 (String name) {4 Super(name);5 }6 Public voidrun () {7 for(inti = 0; I < 50; i++) {8System.out.println (Thread.CurrentThread (). GetName () + ":" +i);9 }Ten } One Public Static voidMain (string[] args) { ADemo1 demo1 =NewDemo1 ("Sony"); - Demo1.start (); - for(inti = 0; I < 50; i++) { theSystem.out.println (Thread.CurrentThread (). GetName () + ":" +i); - } - } -}
sony:0Main:0Sony:1Main:1Sony:2Main:2Sony:3Sony:4Main:3Sony:5Main:4Sony:6Main:5Sony:7Main:6Sony:8Sony:9Sony:10Sony:11Sony:12Sony:13Sony:14Sony:15Sony:16Sony:17Sony:18Sony:19Sony:20Sony:21stSony:22Sony:23Sony:24Main:7Sony:25Main:8Sony:26Main:9Sony:27Main:10Sony:28Main:11Sony:29Main:12Sony:30Main:13Main:14Sony:31Main:15Sony:32Main:16Sony:33Main:17Main:18Sony:34Main:19Main:20Sony:35Main:21stSony:36Sony:37Sony:38Main:22Sony:39Main:23Sony:40Main:24Main:25Main:26Sony:41Main:27Sony:42Main:28Sony:43Main:29Sony:44Main:30Sony:45Main:31Sony:46Main:32Sony:47Main:33Sony:48Main:34Sony:49Main:35Main:36Main:37Main:38Main:39Main:40Main:41Main:42Main:43Main:44Main:45Main:46Main:47Main:48Main:49
View Code
Precautions:
The lock of a synchronized code block can be any object. However, the synchronization lock object must be a multi-threaded shared object, otherwise it cannot be locked.
The lock of a synchronous function is a fixed non-static function of the lock object that is the this object, the static function of the lock object when the class object.
Calling the sleep method in a synchronous code block or a synchronous function does not release the lock object. If the wait method is called, the lock object is freed.
Java Basic Learning-threading