Date Object
methods of the date class
• Construction Method:
-public Date ()
-public Date (long date) to pass a long type argument
• Get time:
-public Long GetTime () returns with a long type
long Cur=system.currenttimemillis ();//Gets the number of milliseconds from January 1, 1970 to the current
Date Format Object (SimpleDateFormat)
• Construction Method:
-public SimpleDateFormat (String pattern)//parameter is the format we need "YYYY-MM-DD HH:mm:ss. SSS "
• Format conversion:
-public Final String format (date date)//Convert the date type to a String type date
-public Date Parse (string sourse)//Converts a String type date to a date type
sdf.setlenient (FALSE);//Turn on Strict mode
generic type
generic <T> wildcard characters? There are two wildcard characters, respectively? Extends class,? Super Class
? Extends class: Can be used for the generic type of the class, can also be used for the generic type of the method, is the upper limit of the set pattern, once the class set the upper limit, then the instantiation
subclasses can only be the generic upper limit of the corresponding class or subclass fun (Message<?extends object> msg);
? Super class: Generic type that can only be used for method parameters, the generic of the accepted parameter can only be the class or the parent of the class fun (Message<?super integer> msg);
New Generics
if you want to define a method that can accept any number of arguments, you can use the new generic to implement public static <t>t[] Fun (t...temp)
{return temp;}
Exception
Eorr and exception are Throwable's subclasses.
Eorr: The error that occurs before the program has been run is that the JVM error is not handled by the capture
Exception: Is the exception that occurs when a program is running, and can be handled by capture.
The program has an exception the JVM will automatically instantiate a corresponding exception object, and then determine if there is an exception to the capture statement throws keyword placed after the method name, once the method is used in the keyword, then the exception in the method will be thrown up, to the call to handle the exception.
The throw keyword position is in the method body, and the exception is thrown manually.
exception is an exception that requires mandatory processing, runtimeexception does not require mandatory handling and can be selectively treated
Assertion
The assert keyword is a representation assertion introduced in the jdk1.4 version
assert num==20; (Num's value is a)
Threads and Processes
a process is the carrier of a thread, a process consists of multiple threads, the thread is attached to the thread, and once the process is closed, the thread does not exist.
The system distinguishes between threads by the name of the thread, so how do you set and get the name of the thread?
-public final String getName () Gets the name of the thread
-public final void SetName (String name) sets the name of the thread
-public Thread (Runnable target,string name) initializes the threads and sets the name
-thread.currentthread (). GetName () Gets the name of the running thread
when you run a Java program using Java commands, the JVM starts a process that starts at least two threads
-The main method is a thread
-GC garbage Collection thread
The sleep of a thread
Thread.Sleep (number of milliseconds);
priority of the thread
threads have three priorities, and the higher the priority, the more threads are executed, but this is just probably not necessarily
• High priority: public static final int max_priority=10
• Medium Priority: public static final int norm_priority=5
• Lowest Priority: public static final int Min_priority=1
-Set priority public final void setpriority (int newpriority)
-Get priority public final int getpriority
Multi-Threading Implementation
to implement a thread, there are two ways of JDK1.5 before you
• Inheriting the thread class, the thread class is a class that supports threading operations, as long as the subclasses of that class can implement all the operations of multithreading
• Implement runnable interface
The callable interface can also be implemented after JDK1.5, but it is currently used in the development of the previous two
The starting point of a Java program is the main method (actually called the main thread), the other threads that are started in the main method are called child threads, and of course they also have their own starting point method, the starting method is the Run method, run () needs to overwrite, After booting does not reflect the concurrency of multithreading, but orderly, the root cause is to use the run () to start the thread,
so use the start () method when you start the thread.
Start () method
The start () method invokes the Start0 () method at startup, which has no method body, similar to an abstract method, and uses native, a technique called JNI (Java Native Interface) technology in Java development. This technology is the use of Java programs to invoke the local operating system function, we start the thread, the operating system must allocate resources for each thread, then in the allocation due to the operating system support is different, so each operating system allocation of resources differently, then the Start0 () method can not write dead, Only one standard can be defined, and the implementation of the specific allocation method has the JVM according to the operating system different implementation of different distribution, which is also a manifestation of Java portability.
to start multithreading you must use the start () method, and the start () method calls Start0 () to complete the allocation of resources after the system automatically calls the run () method.
runnable Interface
There is no start () method in the Runnable interface, but in the thread construction method, we can pass the Runnable interface as a parameter. Public Thread (Runnable target) {}
Inherit thread: This method has the limitation of single inheritance, and it is not convenient to implement data sharing between threads .
implement Runnable interface: There is no single inheritance limitation, and can easily realize the sharing between data, realize multi-threading, using the way to implement Runnable interface is the best.
Synchronization of Threads
If threads are out of sync, there is a risk when multiple threads access Unified data
-use synchronous code blocks
Syntax: synchronized (this) {...}
-Using the synchronization method
syntax public synchronized void run () {...}
the negative effect of synchronization
• With synchronization, the execution efficiency of the code is reduced because the current thread waits for the previous thread to execute before it can be executed.
• With synchronization, there are sometimes deadlocks (but this is a very small probability)
Multi-threading producer, consumer model
Class Publicbox {//product private int apple = 0; Public synchronized void Increace () {while (Apple ==5) {try {wait (); } catch (Interruptedexception e) {e.printstacktrace (); }} apple++; System. Out. println ("Build apple success! " ); Notify (); Public synchronized void Decreace () {while (Apple ==0) {try {wait (); } catch (Interruptedexception e) {e.printstacktrace (); }} apple--; System. Out.println ("Consumer apple success!") " ); Notify (); }} class Producer implements Runnable {//producer private Publicbox box; public Producer (publicbox box) { this. box = box; @Override public void, run () {for (int i=0;i<10;i++) {try {System. println ("Pro I:" +i); Thread. Sleep (30); } catch (Interruptedexception e) { E.printstacktrace (); } box.increace (); }}} class Consumer implements Runnable {//Consumer private publicbox box; public Consumer (Publicbox box) {T His. box = box; @Override public void, run () {for (int i=0;i<10;i++) {try {System. println ("con:i" +i); Thread. Sleep (30); } catch (Interruptedexception e) {e.printstacktrace (); } box.decreace (); }}}public class Test{public static void Main (String []args) {Publicbox box= new Publicbox (); Consumer con= new Consumer (box); Producer pro= new Producer (box); Thread t1= new Thread (con); Thread t2= new Thread (PRO); T1.start (); T2.start (); }}
When a thread accesses the synchronization method of an object, if the thread sleeps with sleep after it enters the method, no other thread can access the object's synchronization method during hibernation, that is, sleep does not release the lock when it sleeps.
When a thread enters the synchronization method of an object and uses the wait mode to hibernate, during hibernation, other threads can access all the same methods of the object, saying that a thread that uses the wait method to hibernate can release the lock
sleep:
|-sleep () is the thread method
|-threads that sleep with sleep automatically wake up
|-Threads sleeping with sleep do not release locks
Wait ():
|-wait () is a method in the Obejct class
|-Threads using wait hibernation need to wake up using the Notify or Notifyall method
|-threads that use wait hibernation release the lock.
Please analyze the code output "A" and "B "How many times?"
Class Productor implements runnable{ @Override public void Run () {for (int i=0;i<50;i++) { try { Thread.Sleep (+); } catch (Interruptedexception e) { e.printstacktrace (); } System.out.println ("A");}} Class Customer implements runnable{@Override public void Run () {for (int i=0;i<50;i++) { System.out.println ("B");}}} public class Test {public static void Main (string[] args) throws Exception { thread th1=new thread (new producto R ()); Thread Th2=new Thread (new Customer ()); Th1.setdaemon (TRUE);//And A is set to the daemon thread th1.start (); Th2.start (); }}
Answer: The above code output "A" is indeterminate, the output "B" is 50 times
The reason is that the thread of output A is the daemon thread, and B's thread is a non-daemon thread (user thread)
The daemon thread serves non-daemon threads, so when there is no non-daemon thread in the JVM, all the daemon threads will end,
Even if the code in the Run () method in the daemon thread is not finished, it will be forced to end. But the non-daemon thread is bound to execute,
The above code A is output by the daemon thread, B is output by the non-daemon thread, so the number of a is variable and the number of B is 50 fixed
Our most common typical daemon thread is the CG garbage collection thread.
Java Fundamentals (iii)