Article Directory
basis
Although java can create multiple threads by inheriting the Thread class and implementing the Runnable interface .
But Runnable is more convenient and easier to realize resource sharing than Thread, so Runnable interface is usually used.
note:
- Multi-threaded start: call the start method , and automatically call the run method with a new process.
(If the run method is called directly, it will become serial execution, and the main function will not continue to execute downwards) - The class that implements Runnable must first be converted to the Thread class to use the start() method.
- The same object can only be started once.
Multi-thread management: Threads should avoid passive suspension and termination, but should take an active approach.
Information Sharing
In Java, information sharing is achieved through shared variables.
Note: Information sharing has the problem of non-synchronization, so it can't just share variables.
solution:
- Use
volatile
keywords for variables .
Once the variable identified by volatile changes, all threads can immediately see the change. - Use
synchronized
keywords for code blocks/functions so that only one thread can enter the block at a time (mutexes).
Common functions
对象名.start();
Thread.currentThread().getName();//返回线程名字,要写getName方法
Thread.sleep(5000);//休眠5000ms
notifyAll();//通知所有线程
Thread management
Example:
Daemon thread
Set a thread as a daemon thread:
Once set as a daemon thread, the thread must end when the main thread ends.
Note: The daemon thread should never access resources, because the daemon thread can easily be terminated passively.