Dark Horse programmer-APIs commonly used in Java with multiple threads

Source: Internet
Author: User
Tags thread stop

 

----------------------
Android training and Java training. We look forward to communicating with you! ----------------------

Java Multithreading
The first way to create a thread: Inherit the Thread class
Steps:
1. Define class to inherit from thread
2. Rewrite the run method in the Thread class
Objective: To store custom code in the run method for threads to run.
3. Call the start method of the thread. This method has two functions: Start the thread and call the run method.

Default name: thread-number starts from 0
Static thread currentthread (): Get the current thread object
Getname (): Get the thread name

* *** A simple ticket selling program.

Method 2: Create a thread. Method 2: implement the runnable interface.
Steps:
1. Define the class to implement the runnable interface
2. overwrite the run method of the runnable interface.
3. Create a thread object through the Thread class.
4. Pass the subclass object of the runnable interface as an actual parameter to the constructor of the thread class.
5. Call the start method of the thread class to enable the thread and call the run method of the runnable interface subclass.

There are two differences:
Inherited thread: the thread code is stored in the thread subclass run method.
Implement runnable: Run method of a subclass with an interface.

Synchronized (object)
{Code to be synchronized}
Objects are like locks. The thread holding the lock can be executed in synchronization.
The thread that does not hold the lock cannot even obtain the execution right of the CPU, because the lock is not obtained.

Prerequisites for synchronization:
1. There must be two or more threads.
2. Multiple Threads must use the same lock.

Ensure that only one thread is running in synchronization.

Benefit: it solves the security problem of multithreading.
Disadvantages: multiple threads need to judge the lock, which consumes more resources,

The lock of the synchronous function is this
What is the lock used after the synchronization function is statically modified?
The lock used by the static synchronization method is the bytecode file object of the class of the method.Ticket. Class

Singleton design mode: hungry and lazy (when multithreading)
1. Delayed loading 2 inefficient 3 locking for bytecode file objects

Multithreading-deadlock: Example: Nested synchronization in synchronization, different locks

Wait for the wake-up mechanism. Thread Pool.
Wait ()
Notify ()
Policyall ()

Why do the methods of these operation threads need to be defined in the object?
These methods must mark the locks held by the threads they operate on during synchronization. Only the waiting threads of the same lock can be awakened by notify of the same lock. It is not allowed to wake up threads with different locks. That is to say, waiting and waking must be the same lock. Therefore, the methods of any object are defined in the object.

Producer consumer example: New Features of jdk1.5
Lock replaces synchronized condition Await signal signalall
Replace wait policy policyall

Thread stop method: You can call interrupt to end the run method.

Daemon: T. setdaemon (true) background process. The process automatically ends after the foreground ends.
Join () waits for the thread to terminate and grabs the CPU execution right
Priority setpriority (1, 5, 10)
Yield method: Pause the current execution
Thread group concept

Bytes -----------------------------------------------------------------------------------------------------
Java API:

Detailed query document
String
Stringbuilder: method call chain
Basic data type packaging
----------------------------------------------------
Collection framework: top-level collection
Why are there so many containers?
Because each container stores data differently.
This storage method is called: Data Structure

List: The elements are ordered and can be repeated. Because the collection system has indexes.

Special method: the method with a badge.
Arraylist: the underlying data structure is an array structure. The query speed is very fast. However, adding, deleting, and deleting are slow. Thread not synchronized
1. Add an element to store references
2. Obtain the number. Size ();
3. Delete element remove clear
4. Determine the element contains
Intersection: retainall
Removeall
Iterator: iterator
Gets the iterator used to retrieve the elements of the set.
Listiterator is a sub-interface of iterator.
During iteration, elements in the set cannot be operated through the method of the Set object. You can only use the iterator to operate elements.

Slow list: the bottom layer uses the Linked List data structure, which provides fast addition and deletion speeds and slow query speeds. The difference between add get and remove is added. When you obtain an object, you do not need to delete it.
The empty list of PEEK poll is provided after 1.6. If no exception is thrown, null is returned.
Vector: The underlying layer is the array data structure and thread synchronization. Replaced by arraylist. Enumeration is a unique method of retrieving a vector. It is generated by the iterator.

------------------------------------------------
Set: elements are unordered and cannot be duplicated.
Hashset: the underlying data structure is a hash table.
Ensure uniqueness: hashcode and equals methods. Pay attention to the format of rewrite. The thread is not synchronous.

Treeset: sorts the elements in the Set set.
Add custom object: Implements comparable forces students to have a comparison

. The underlying data structure is a binary tree and a red/black tree. Uniqueness assurance: compareto Method

Return 0;
The first method of treeset sorting: comparing elements is called natural order.

Compareto method in comparable. Implement comparable
The second sorting method of treeset.
When the element itself is not comparable. Or not when necessary.
In this case, the set itself is compared. The comparator is defined, and the comparator object is passed as a parameter to the constructor. Comparator interface, rewrite compare Method

** Sorting: when the primary conditions are the same, the secondary conditions are sorted.

Generic: a new feature is available in jdk1.5 and later versions to solve security problems. It is a security mechanism.
Arraylist <string> Al = new arraylist <string> ();
Benefits:
1. Transfer classcastexception in the running period to the compilation period.
2. This avoids the trouble of forced conversion. <> Used to receive generics.
Iterator <string> it = iterator ();

Generic class: Class util <t> {}
When to define generic classes and when the referenced data types to be operated in the class are uncertain

. Objects are defined earlier to complete expansion. Now define the generic type to complete the extension.

Generic method: Public <q> void show (Q)

Generic definition on the Interface

Generic restrictions: <?> <? Extends person> <? Super E>
Void printcoll (arraylist <...> Al)

-------------------------------------------------
Map set: This set stores key-value pairs. One to one. The key value must be unique.

Map
| -- Hashtable: the data structure of the hash table is at the underlying layer, and null cannot be saved. This set is synchronized by threads. Jdk1.0

| -- Hashmap: The underlying layer is the data structure of the hash table. The null value and the null key are allowed. This set is not synchronized by threads. Jdk1.2
| -- Treemap: The underlying layer is the binary tree data structure. The thread is not synchronized. It can be used to sort keys in the map set. Similar to set. At the underlying layer of set, map sets are used.

Hashmap: replace the old value with the new value.

There are two methods to retrieve a map set:
1. keyset: store all the keys in the map to the Set set. Because set has an iterator. According to the get value of all keys.

2. entryset: <map. Entry <K, V> generic nesting
// Map. Entry is actually an interface, which is an internal interface in the map interface.
Map extension knowledge: Read hashmap <string, hashmap <string, string>

Tool class:
Collections.
Sort (list List)
. Max (collection C)
. Binarysearch: Ordered Set
. Fill replacement
. Replaceall replace
. Reverse reversal
. Reverseorder reverse comparison
Synlist: synchronizedlist () returns thread security
Shuffle random
Arrays:Operation Array
Aslist () converts an array to a list set. ** the addition and deletion methods of the set cannot be used. Because the length is fixed.

Array of collection changes: Method toarray in Collection

1.5 new features:

Advanced for Loop
For (data type variable name: The retrieved collection or array )**

Variable Parameter: Show (Int... arr)

Import static java. util. arrays. *; static import. You can leave the class name empty.

---------------------------------------------------
Other Objects
System:
Get system property information: getproperties ()
Java-dhaha = qqqqq systemdemo

Runtime:Singleton Design Mode
Exec (...) Double slash

Date :.Util .*;
Java. Text .*;
New Date () current time.

Calender:

Math
Random Number of. Random 0-1

 
 

----------------------
Android training and Java training. We look forward to communicating with you! ----------------------

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.