The thread is actually a path of program execution, a process can contain multiple threads, multi-threaded execution can improve program efficiency, with the completion of a number of tasks
Multithreaded application scenarios
- Thunder multi-threaded download together
- Simultaneously processing multiple client requests the server
Multithreading principle (single core CPU)
When running multiple programs on their computers, in fact, cpu can only do a thing to do after a period of time and then for another period of time to do another, but cpu too quickly,
看起来就是同时做很多事
that is multi-threaded In fact只是表面上的多线程
, the underlying cpu or you can only do one thing, but it has a premise that the single core cpu cpu is, if things multicore cpu, then you can really achieve并行
.
Multi-threaded parallel and concurrent difference
- parallel
Two parallel tasks running simultaneously, you need multi-core cpu, how many nuclear on how many tasks in parallel.
- Complicated by
Concurrency is a request to run two tasks, and a processor can only accept a task, to arrange two tasks take turns, due to the relatively short period of time to feel two tasks simultaneously running
- ps
Our so-called multi-threading is complicated by , if you do not use multiple threads, the program is a request for a code, if you use multiple threads, then you can request to run this method, while the other method also request to run, that is to say,
没有使用多线程的话代码是一条一条请求,使用了就是多条同时请求,但底层并不是并行
just cpu processing fast feel.
Multithreaded program implementation 1
1, the definition of class inheritance Thread
2, a method override run
3, the new thread to do write in the run method
4, create a thread object, that is, we defined the object
5, open a new thread (start), the internal method performed automatically run
Multithreaded program implementation 2
1, defining class implements Runnable interface
2, a method override run
3, the new thread to do the run method to uninstall
4, create a Thread object to its constructor method and pass an object that implements Runnable interface class
5, open a new thread using the Thread
Multithreaded program implementation 3
The third interface to create multiple threads
Callable
Created:
1, create a thread class, and Callable <> class and override the inherited method call
2, create a thread pool
3, create a thread object and then use the submit method of adding to the thread pool
The difference between the two implementations multi-threaded (interview may ask)
Inheritance Thread:
Because we created class inherits the Thread class, so when we call to start, run method is executed directly subclass, which is the class we created.
Implement Runnable interface to create the object and pass instantiate Thread constructor:
We are the first to create objects that implement the Runnable interface, and then create a Thread object and objects created before passing Thread constructor, then the Thread class will save the object passed to the member variable, when we call Thread object start when methods, Thread object calls the run method of its member variables, member variables of course, this is what we created an interface that implements the Runnable object
Both implementations multithreaded pros and cons
Inheritance Thread:
Benefits:
you can call a method of Thread, so concise code.Disadvantages:
Since inheriting the Thread method can not inherit from other classes of
Implement Runnable:
Benefits:
Because the interface is more than can be achieved, so you can inherit other parentDisadvantages:
can not directly create objects using the code more complicated
ps:
Personal feeling is actually a supplement to achieve Runnable succession of Thread, look at the situation when you are developing.
The method of the Thread class
- .start()
Open thread, multiple starts are illegal
- .getName()
Get Thread name, the default name from the thread so Thread -0 start
- .setName()
Set thread name
- .c large column javaSE Review - The thread urrentThread ()
Gets the current thread object reference, which thread will get calls where
- .sleep (ms, ns)
Sleeping thread, how much time passed stopped for how long, also can be transferred separately ms
.setDaemon()
Daemon thread, set up a thread after a daemon thread, the thread does not perform alone, when all other non-daemon threads complete execution automatically exit.
- ps:
after all non-daemon thread is finished, there will be a buffer time, buffer time guardian within this thread will run, it is equivalent to a daemon thread can tell when non-daemon thread exits can be pulled out, this is the time to tell the buffer time
- ps:
.join()
This method is called a thread is suspended (write this code thread), waiting for the end of the specified thread, the current thread continues to run again
.join(int)
After waiting for a specified milliseconds continue
- ps:
If you call t.join () method in the main primary, then t wait after the end of the thread execution, the main method will continue, this command is usually used in the main method.
- ps:
.yield()
Comity thread, so the cpu, but also reduce the cpu is to make their execution priority, the execution is to let others
- .setPriority (1-10)
Setting thread priority, default is 5
- .getThreadGroup()
Obtain the group to which it belongs by thread object, the object is returned thread group
SUMMARY synchronization code block
When a number of concurrent threads, cpu will perform the first complete
同步代码块
all the code will be to execute another thread不会这里执行几句代码那里执行几句代码
.
- ps:
it is actually locks
When synchronization is required?
When the multi-threaded, we want a thread in some of the code during execution without switching to another thread work, we need to use synchronized block.
Synchronized block keywords
synchronized
Defined method:
1 |
(Object lock) { |
Sync block (lock) Notes:
1, the lock object may be any object
2, two code blocks need to be synchronized with a lock, or can not achieve the desired effect
3, can not be anonymous object because two anonymous object is simply not an object, that is not the same lock
4, do not lock nesting, or prone to deadlock, since there may be waiting for another situation
How synchronization method definition?
- answer:
Just add the synchronized keyword when you can modification method of
Notes synchronization method:
- Lock object is a non-static method
它自己这个对象
, that is, this - Static method because it is loaded with class and load, so it is the object of it in class
字节码文件
, that object is a static method lock it in class bytecode file
Thread-safety issues
When multiple threads operate on the same data, there may be data security issues
Solution
Analyzing and needs a certain period of operation where the data block plus a synchronization code
Precautions
Lock objects used must be the same lock
建议直接用类的class文件
, if you must use reference data types, you must use static.
Recalling the previous thread-safe class
The method involves thread-safe class data operations are added to the synchronized modification, such as Vector, ArrayList, StringBuffer, StringBuilde
Thread-safe method
.synchronized [here followed by collection type, what type of returns that type of collection]
- ps:
its role is to pass a collection object, came a thread-safe collection object