Java Multithreading and additions

Source: Internet
Author: User
Tags generator thread class

Process
A running application is called a process, and each process runs with its own address space (memory space)
IE browser can be seen in the task tube
Operating systems are supported for multiple processes

Thread
A thread is a lightweight process, a control unit that is responsible for program execution in a process
Thread does not have a separate address space (memory space)
Threads are created by the process (parasitic in process)
A process can have multiple threads, at least one thread
Threads have several states (new, Ready runnable, run running, Block blocked, death dead)
Multiple threads are opened to run multi-part code at the same time, and each thread has its own running content, which can be called the task the thread is to perform (put in the Run () method)

Multithreading
Multithreading refers to a program that contains multiple execution streams, in which multiple different threads can be run concurrently to perform different tasks, that is, allowing a single program to create multiple threads of parallel execution to accomplish their tasks.

The benefits of multithreading
Java supports the writing of multithreaded programs;
The greatest advantage of multithreading is that multiple tasks can be executed concurrently;
Multithreading can minimize the idle time of the CPU, thereby increasing CPU utilization.

The disadvantage of multithreading
Threads are also programs, so threads need to consume memory, and more threads consume more memory;
Multithreading requires coordination and management, so CPU time is required to track threads;
Access to shared resources between threads affects each other, and the issue of competing shared resources must be resolved;
Too many threads can cause control to be too complex and can eventually cause many bugs.

Two ways to create threads in Java
The first type: How to inherit the thread class
Step: 1) Create a class to inherit the thread
2) Overwrite the Run method to store custom code that is multithreaded to be executed.
3) Create the class in the main function
4) Call the thread using the start () Square 1 method (the Start method has two meanings: 1, start multithreading. 2, call the Run method in the thread)
The second type: How to implement the Runnable interface
Steps:
1) Create class implementation runnable interface
2) Implement the Run method in the Runnable interface
3) Create thread object
4) The construction method of passing the Runnable object as the actual parameter to the thread
5) Call the Start method of the thread class to automatically execute the Run method in the Runnable object

Get the name of the thread: GetName (), thread method
Currently executing thread: CurrentThread ()
Set the name of the thread: SetName ("name");

Thread Priority:
The thread class has the following three static variables to represent a priority
Max_priority: The value is 10, which indicates the highest priority
Min_priority: The value is 1, which indicates the lowest priority
Norm_priority: The value is 5, which indicates the default priority
Set priority by Number: SetPriority (1);
Set priority with static variables: setpriority (max_priority);
Get priority: GetPriority ();

Causes of thread safety problems:
Multiple thread operations sharing data
There are multiple thread codes for shared data
When a thread executes multiple code processes that share data, other threads take part in the operation, causing the thread's security problems to occur

There are two methods of thread synchronization:
1. Synchronous statement BLOCK: Exclusive access to resources of this area block only
Synchronized (Shared object name) {
Code snippets that are synchronized
}
It locks the current object that corresponds to the shared object name, which is typically added to the Run method in a thread that implements the synchronization block.
2. Use synchronized to modify the method:
Access modifier synchronized Data return type method name () {
...
}
It locks the object that invokes this synchronization method. Other threads cannot access any one of the synchronized methods in this object at the same time.

Concept of thread deadlock
Refers to two threads that hold each other's shared resources dependent on each other, causing infinite blocking. The root cause of deadlocks is the inappropriate use of the SYNCHRONIZED keyword to manage thread access to specific objects.

How to resolve a deadlock
Let the thread hold a separate resource.
Try not to use nested synchronized statements.
Deadlocks should be minimized by the excellent design of the dead lock.

Thread communication: Refers to a number of threads through the message delivery implementation of each other, scheduling, that is, the interaction between threads.
The method of the object class wait ()--causes the current thread to wait, notify ()--wakes up the waiting thread, and uses it together with synchronized to achieve the effect

Sleep (): The static method of thread, which must be specified in time. Put this thread into sleep mode and wake up in time. The sync lock is not released.
Wait (): The method of object, which can be specified or not to specify a time. Let this thread into the waiting state, need someone to wake up notify (). The sync lock is released.

Yield ()
Thread a name. Yield ()
Thread A gives up the use of the CPU for other threads to execute (not absolute)
Note: These two threads must be of the same priority

Join ()
Join: Which thread calls the join () method, which thread executes first,
1) When a thread A calls the join () method, the main thread executes after the
2) Two threads A and b all call the Join () method, a is executed against each other, and the main thread executes the last
Note: The join () method does not work until it is written after start ()

Setdaemon ()
Daemon Thread:
The daemon thread is the daemon main thread (main), and the main thread ends, regardless of the current state of the daemon.
A thread to invoke Setdaemon (true);//The daemon thread when the parameter is True
Note: The Setdaemon (true) method must be used before start ()

c/s difference?
c/S (client/server): The structure of software, client server to write, high development costs, maintenance trouble, the benefit is that the client can share a part of the operation of the local
b/S (browser/server): This structure software only develops the service side, does not develop the client, because the client is replaced directly by the browser, the development cost is low, the maintenance is simpler, the disadvantage is that all operations are done on the server side, increasing the burden on the service side

String StringBuffer StringBuilder
For a summary of the three uses:
1. If you want to manipulate a small amount of character data, or if you do not modify the string in many cases, the most suitable
2. If you want to manipulate a large number of character data, or the string modification is more than the case with Bufferbuilder because it has a buffer, because the StringBuilder thread is not all Ann, so when our project is multi-threaded, do not use Bufferbuilder, StringBuilder execution efficiency is faster
3. Multi-threaded operation string buffer operation large amount of data = StringBuffer

Clone () Creates and returns a copy of this object.
You can clone an object that creates a copy of an object, and the class must implement the Cloneable interface to enable the object of the class to be cloned.

BigInteger class
Located in the Java.math package
Used to calculate very large integers.
BigInteger big1 = new BigInteger ("12345676134896413132");
BigInteger big2 = new BigInteger ("123");
BigInteger big3= big1.multiply (BIG2);
System.out.println (BIG3);

BigDecimal class
Located in the Java.math package
Used to calculate very large floating-point numbers.
BigDecimal big1 = new BigDecimal ("12345676134896413132.02");
BigDecimal big2 = new BigDecimal ("123.36");
BigDecimal big3= big1.multiply (BIG2);
System.out.println (BIG3)

The difference between collections and collection?
Collection: The interface of the collection class
Collections: The class of operation set, there are many static methods in this class, most of these methods are for list operation, including sorting, rearrangement, searching and so on.
The arrays class defines a method for manipulating an array, including sorting the array for lookups.
Arrays class:
Sort: Sort (): Sort the contents of an array in ascending order
Find: BinarySearch (array): Use the contents of an array to find (binary lookup), and note that the values in the arrays are in order (from small to large or from large to small)
Collections class:
Sort: Sort (): Sort the contents of an array in ascending order
Find: Binaryserach (collection): Use the contents of an array to find (binary lookup), and note that the values in the arrays are in order (from small to large or from large to small)

Encapsulation:
Encapsulation is an important feature of object-oriented, in Java, an object is a set of variables and methods of encapsulation, where variables describe the state of the object, the method describes the behavior of the object. Through the encapsulation of objects, the user does not have to understand how the object is implemented, only need to interact with the object through the interface provided by the object, the encapsulation realizes modularization and information hiding, which is advantageous to the portability of the program and the management of the object.
In Java, the encapsulation of an object is implemented in the following 2 ways:
1) encapsulation through the package, which defines the access rights of the program class
2) encapsulation is achieved through access to the members of a class or class.

Random
The random class, which is used to generate stochastic numbers.
Located under the Java.util package
Construction Method Summary
A new random number generator is created by random ().
The random (long seed) creates a new random number generator with a single long seed.
Method:
Intnextint () returns the next pseudo-random number, which is an int value that is evenly distributed in the sequence of this random number generator.
Intnextint (int n) returns a pseudo-random number, which is an int value that is evenly distributed between 0 (inclusive) and the specified value (not included) from this random number generator sequence.
Longnextlong () returns the next pseudo-random number, which is a long value that is uniformly distributed from this random number generator sequence.
Boolean Nextboolean () returns the next pseudo-random number, which is a Boolean value derived from the uniform distribution of this random number generator sequence.
Voidnextbytes (byte[] bytes) generates a random byte and places it in a user-supplied byte array.
Double nextdouble () returns the next pseudo-random number, which is a double value that is evenly distributed between 0.0 and 1.0, taken from this random number generator sequence.
Floatnextfloat () returns the next pseudo-random number, which is a float value that is evenly distributed between 0.0 and 1.0, taken from this random number generator sequence.

The difference between heap and stack (stack)
1) Deposit local variables, array or object reference variables, and methods in the stack
2) The heap holds the objects (and global variables) and arrays created by new
3) data in the stack is automatically cleared after the scope is exceeded
4) The data in the heap is not automatically purged after the scope is exceeded, and is recycled by the garbage collector
5) Stack advanced after out, heap first out

Java Multithreading and additions

Related Article

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.