1. The difference between run () and start ()
2. Basic thread properties and methods
- ID: An incremented integer, one for each thread created
- Name
- Priority: from 1 to 10, the default is 5, which is mapped to the priority in the system. The larger the number, the higher the priority
- State:
-
- NEW: Start not yet called
- Runable: Executing run or waiting for Cup allocation time
- BLOCKED: Blocked
- Waiting: Blocked
- Timed_waiting: Blocked
- TERMINATED: End
- Whether to Daemo threads
- Sleep method, Unit is milliseconds
- Yield method, it is recommended that the CPU
- Join method, join (0) or join () indicates an indefinite wait
- Obsolete method Stop (), suspend (), resume (), obsolete, should not be reused
3. Race condition: When multiple threads access and manipulate the same object, the final execution result is related to the execution timing and may or may not be correct.
Solution:
- Using the Synchronized keyword
- Using Display locks
- Using Atomic variables
4. Memory Visibility: Multiple threads can share access and manipulate the same variables, but one thread changes to a shared variable, and the other thread doesn't have to see it right away, or even never see it. Because it involves registers and cache levels.
Solution:
- Using the volatile keyword
- Using the Synchronized keyword
5, synchronized
Synchronized can be used to modify an instance method of a class (protect this), a static method (a protected class object), a code block (arbitrary object).
Synchronized protects objects, not code, as long as the synchronized method of the same object is accessed, and even different code is executed in a synchronized order.
So multiple threads can execute the same synchronized instance method at the same time, as long as they are accessing different objects.
Reentrant: This is achieved by recording the holding thread of the lock and the number of holds.
Guaranteed memory Visibility: When a lock is released, all writes are written back into memory, and when the lock is acquired, the latest data is read from memory.
If only the memory visibility is guaranteed, the cost of synchronized is a bit high,
Java Programming Logic--15 concurrency