Javase Second study essay (iv)

Source: Internet
Author: User
Tags garbage collection thread class thread stop

--------------------------------------------------------------------------------------------------------------- ------------------------------------------
/*
3, requirement description
Define a thread A, output an integer between 1 and 10,
Define a thread B, reverse output 1 to 10 integer, require thread A and thread B alternating output
*/

public void Wu () {Runnable R1 = (), {Threada ();        };        Runnable r2 = (), {threadb ();        };        New Thread (R1). Start ();    New Thread (R2). Start ();    } private int numa = 11;    private int numb = 0;            Public synchronized void Threada () {while (numa + numb = = && Numa > 1) {numa--;                try {System.out.println ("Threada:" + numa);            This.wait (3);            } catch (Exception e) {e.printstacktrace ();            }finally {this.notifyall ();            }}} public synchronized void Threadb () {while (Numa + numb + 1== && Numb < 10) {            numb++;                try {System.out.println ("threadb:" + numb);            This.wait (3);            } catch (Exception e) {e.printstacktrace ();            }finally {this.notifyall ();     }   }    } 

  


--------------------------------------------------------------------------------------------------------------- ------------------------------------------
1.two ways to implement multi-threading
Multithreading consists of two implementations, one is to inherit the thread class rewrite the run () method, and the other is to implement the Runnable interface implementation of the run () method, The object created by Runnable is used as a task object when the thread object is created, and the Runnable object is passed in using. Start () execution threads;
The methods of synchronization are synchronized methods and synchronized code blocks, and Wait () and notify () Notifyall ();
2.The basic concepts of threads, the basic state of threads, and the relationship between States
A thread is a basic unit of CPU scheduling, and a process is a unit of system resource scheduling at least one thread in a process is responsible for executing the program; Normally, running a program has two threads a main thread a GC thread (garbage collector);
The basic state of a thread is: Create, ready, execute, block, stop;
allocating memory for thread objects when creating a thread this is the creation state,
When the start () method of the thread is called, the thread enters the ready state.
When the thread starts running the run () method, the thread in the ready state can go to the running state, and only one thread is in this state at any time in a single-CPU run environment.
Blocking states include waiting for blocking (wait ()), synchronous blocking (synchronized), and other blocking (sleep () or IO requests ...) when the blocking is complete and re-enters the ready state waiting for the CPU to dispatch
This thread ends when the code in the Run () method finishes executing or encounters an unexpected exception that exits the run () method at this point in the stop state.
3. What are the similarities and differences between synchronous and asynchronous, and under what circumstances are they used separately? An example is described.
The difference between synchronous and asynchronous is whether the operation of the resource is simultaneous, in the case of a shared resource, only the thread that obtains the synchronization lock can manipulate it at the same time. Other threads that do not have a lock enter the blocking state to wait for the current thread to complete the shared resource operation before entering and executing the code. Asynchronous situations can be arbitrarily accessed for shared resources without querying whether other threads are accessing or manipulating the resource.
Thread synchronization is required when multiple threads need to operate on the same shared resource, and no synchronization is required when there is no action on shared resources between multiple threads; When an application calls a method that takes a long time to execute on an object and does not want the program to wait for the method to be returned, it should use asynchronous programming, which is often more efficient in many cases with asynchronous approaches.

4.The difference between sleep () and wait ()
When Thread.Sleep () executes, the thread does not release the lock and enters a specified duration of hibernation, and after the time expires, the thread enters the ready state, and if the thread has a higher priority than the running state, it will enter the run state. While that thread enters the blocking state or the running thread enters the blocking state, this thread grabs the CPU runtime into the running state;
When Object.wait () executes, the thread frees the object lock and enters the wait pool, which is only re-entered in the Ready state after the Notify method or Noitfyall () method is emitted against the object;
5. start a thread with run () or start ()?
Use the start () method to start a thread so that the thread is ready to wait for CPU scheduling to execute; the run () method does not allow this thread to enter a ready state, and the run () method can produce a flag that must be exited to stop a thread

6. Reasons for a different sync problem: Multiple threads sharing a single piece of data
Workaround: Add a synchronous block of code to the code, allow only one next time and concept to perform the task, the other threads will not be able to enter the task code area, only when the front thread completes the task, release the lock other threads to enter this block of code and perform the task
* Synchronizing blocks of code, equivalent to mutually exclusive relationships between threads
* Requirements for the so-called lock: The lock must be able to be shared by multiple threads, must be an object; For example: obj This object.class, when using thread synchronization lock must try to reduce the lock granularity to improve efficiency, try to use a small range of objects to act as a lock, the scope is too large to cause unnecessary trouble

7. Join () and yield () {http://www.importnew.com/14958.html I was too lazy to copy all two addresses ...}

A little background for Java thread scheduling in a variety of threads, the Java Virtual machine must implement a prioritized, priority-based scheduler. This means that each thread in a Java program is assigned a certain priority, expressed as a positive integer within the defined range. The priority can be changed by the developer. Even if a thread has been running for a certain amount of time, it is important that the Java Virtual machine does not change the value of its priority

Precedence because the convention between the Java virtual machine and the underlying operating system is that the operating system must choose a Java thread with the highest priority. So we say Java implements a priority-based scheduler. The scheduler is implemented in a prioritized manner, which means that when a thread with a higher priority arrives, it will be interrupted (preempted) regardless of whether the low-priority thread is running. This Convention is not always the case for the operating system, which means that the operating system may sometimes choose to run a lower-priority thread. (I hate multithreading for this, because that doesn't guarantee anything)

Note that Java does not qualify threads to run on a time slice, but most operating systems have this requirement. Confusion often arises in terminology: preemption is often confused with time slices. In fact, preemption means that only threads with high priority can take precedence over low-priority threads, but they cannot preempt each other when the threads have the same priority. They are usually controlled by time slices, but this is not the Java requirement.

Understanding thread Precedence
Next, understanding thread prioritization is an important step in multithreaded learning, especially in the work process of understanding the yield () function.

Remember that when the priority of a thread is not specified, all threads carry a normal priority. The
priority can be specified in a range from 1 to 10. 10 represents the highest priority, 1 represents the lowest priority, and 5 is the normal priority. The
remembers that the highest priority thread is given priority at execution time. However, there is no guarantee that the thread will enter the running state at startup.
threads that are currently running may always have a higher priority than threads in the thread pool that are waiting for a chance to run. The
is determined by the scheduler which thread is executed. The
T.setpriority () is used to set the priority of the thread. The
remembers that the thread's priority should be set before the threads Start method is called.
You can use constants, such as Min_priority,max_priority,norm_priority, to set the priority

Yield () method
In theory, yield means letting go, giving up, surrendering. A thread that calls the yield () method tells the virtual machine that it is willing to let other threads occupy its place. This indicates that the thread is not doing something urgent. Note that this is only a hint and is not guaranteed to have no effect. It is only into the ready state, will not abandon the thread synchronization lock;

Join () Method: can also be written as join (num MS)
Definition: A method of a thread instance the join () method allows one thread to execute after another thread has finished. If the join () method is called on a thread instance, the currently running thread will block until the thread instance finishes executing.
Principle: Once a thread calls the join () method, his priority will be higher than the thread that called him. Call his line routines and so on when the current thread finishes executing.
Note: Priority is only higher than calling his thread. There is no effect on the other threads. The join method must be executed after the thread has started working.


/**
* Single pattern lazy mode use double check lock to minimize thread safety judgment times to improve efficiency
*/

Class SingleInstance {    private static singleinstance singleInstance2 = null;    Private SingleInstance () {} public    static SingleInstance getsingleinstance () {        if (SingleInstance2 = = null) {            synchronized (singleinstance.class) {                if (SingleInstance2 = = null) {                    SingleInstance2 = new SingleInstance ( );                }            }        }        return singleInstance2;}    }

  



1. Multithreading Multi-Consumer multi-producer (consumer products to 0 or some extent to start production, production to a certain extent began to stop production)

public class Demo2 {public static void main (string[] args) {obj o = new OBJ ();        Thread P1 = new Thread (new Producer (o));        Thread P2 = new Thread (new Producer (o));        Thread p3 = new Thread (new Producer (o));        Thread P4 = new Thread (new Producer (o));        Thread C1 = new Thread (new Customer (o));        Thread C2 = new Thread (new Customer (o));        Thread C3 = new Thread (new Customer (o));        Thread C4 = new Thread (new Customer (o));        P1.start ();        C1.start ();        P2.start ();        C2.start ();        P3.start ();        C3.start ();        P4.start ();    C4.start ();    }}class OBJ {public int num = 0;    Public obj () {} public obj (int num) {this.num = num;    } public int Getnum () {return num;    } public synchronized void setnum (int num) {this.num = num;    }}class Producer implements Runnable {volatile Obj o = null;    Public OBJ Geto () {return o; } public void SetO (OBJ o) {THIS.O = O;    Public Producer () {} public Producer (Obj o) {this.o = O; } @Override public void Run () {while (true) {if (O.getnum () >) {Synchroniz                    Ed (o) {System.out.println (Thread.CurrentThread (). GetName () + "wake-up consumption stop production");                    O.notify ();                    try {o.wait ();                    } catch (Interruptedexception e) {e.printstacktrace ();                    }}} if (O.getnum () <) {synchronized (o) {                        if (O.getnum () <) {O.setnum (O.getnum () + 1);                    System.out.println (Thread.CurrentThread (). GetName () + "production, remaining" + o.getnum ());    }}}}}}class Customer implements Runnable {volatile Obj o = null; Public Customer (Obj o) {this.o = O;    Public Customer () {} public Obj Geto () {return o;    public void SetO (Obj o) {this.o = O;        } @Override public void Run () {Long a = System.nanotime (); while (true) {if (O.getnum () <= 0) {synchronized (o) {System.out.printl                    N (Thread.CurrentThread (). GetName () + "wake-up production stop Consumption");                    O.notify ();                        try {o.wait ();                    A = System.nanotime ();                    } catch (Interruptedexception e) {e.printstacktrace (); }}} if (O.getnum () > 0) {synchronized (o) {i                        F (o.getnum () > 0) {o.setnum (O.getnum ()-1);                    System.out.println (Thread.CurrentThread (). GetName () + "consumption, also remaining" + o.getnum () + "" + (System.nanotime ()-a)); }                }           }}}}2. multithreaded multi-consumer multi-producer (no matter how many producer consumers, produce one-time consumption) public class Demo4 {public static void main (string[] Arg        s) {dat d = new Dat ();        Runnable r1 = new P (d);        Runnable r2 = new C (d);        thread T1 = new Thread (r1);        Thread t2 = new Thread (r2);        thread t3 = new Thread (r1);        thread T4 = new thread (r2);        T1.start ();        T2.start ();        T3.start ();    T4.start ();    }}class Dat {int num = 2;    Private lock lock = new Reentrantlock ();    Private Condition C1 = Lock.newcondition ();    Private Condition C2 = Lock.newcondition ();                public Void Inc. () {while (true) {try {lock.lock ();                while (num% 2 = = 0) {c1.await ();                } num++;                System.out.println (Thread.CurrentThread (). GetName () + "INC" + num);            C2.signal ();         } catch (Interruptedexception e) {e.printstacktrace ();   } finally {Lock.unlock ();                }}} public void Dec () {while (true) {try {lock.lock ();                while (num%2! = 0) {c2.await ();                } num--;                System.out.println (Thread.CurrentThread (). GetName () + "DEC" + num);            C1.signal ();            } catch (Interruptedexception e) {e.printstacktrace ();            } finally {Lock.unlock ();    }}}}class P implements Runnable {Dat d = null;    @Override public void Run () {d.inc ();    } public P (Dat d) {this.d = D;    }}class C implements Runnable {Dat d = null;    @Override public void Run () {D.dec ();    } public C (Dat d) {this.d = D; }} (another way, tagged by) try {Lock.lock (), while (flag = = False) {try {//wait (); conditioncon.await ();} catch ( Interruptedexception e) {//TODO auto-generated catch BLOCKE.PRIntstacktrace ();}} System.out.println (Thread.CurrentThread (). GetName () + "consumed:" +name+ "Number of products:" +count+ "The price of the product:" +price "; flag =!flag;// Wake-Up Production line//notify ();//notifyall (); conditionpro.signal ();} finally {Lock.unlock ();}

  



* Thread stop: How to end his task
* 1. End thread with an identity
* 2. Call the Stop method--there are inherent security issues that the system is not recommended to use.
* 3. Call the Interrupt () method
Thread.Interrupt ();///when the main thread executes to a stage, the interrupt method of the child thread is dropped, and the child thread's exception (interruptedexception) is triggered, so that the child thread's task ends and the child thread ends.

Daemon Threads
* Daemon Thread: Equivalent to a background thread. Depends on the foreground thread. Normally, when the current thread ends, no matter the threads of the guard line ends, it will end immediately.
* Typical daemon thread: garbage collection thread
/*
* When the program calls the Setdaemon method, and the parameter is set to True. The current thread becomes the Guardian line layer.
* Note: This method must be called before the Start method
*/
Thread.setdaemon (TRUE);
Thread.Start ();
--------------------------------------------------------------------------------------------------------------- ----------------------------------------------
* Stream (IO stream): Input-outputstream, Function: Enables data transfer between two devices
*
* Device: Disk (hard disk), memory, keyboard, file, network, console
* Network: Online resources outside the current host
*
Classification
* Depending on the mode of operation: the input stream and the output stream are all memory-referenced objects, input or output
* Depending on the type of data: byte stream and character stream
*
* Byte stream: bytes transmitted, can manipulate any type of data------audio, video, files, pictures, etc.
* Character stream: bytes are transmitted, different points are encoded in the transfer process, so that our operation more convenient------text
*
* Due to memory for reference
* Byte stream:
* Byte input stream: InputStream
* Byte output stream: OutputStream
*
* Two parent classes of character streams:
* Character read stream (data input into memory): Reader
* Character writes out stream (takes data out of memory): Writer
* There is also a pointer within the flow ~

Character stream and byte stream specific point difference (https://www.cnblogs.com/wsg25/p/7499227.html)
1. The byte stream is also called the raw data, which requires the user to read the code and convert it accordingly. The implementation of the character stream is based on automatic conversion, and the data is automatically converted into characters according to the JVM's default encoding when reading the data.
2. The character stream processing unit is a 2-byte Unicode character that operates on a character, character array, or string, and the byte stream processing unit is 1 bytes, manipulating bytes and byte arrays. So the character stream is made up of characters that the Java Virtual machine converts bytes into 2-byte Unicode characters.
3. Byte stream can be used for any type of object, including binary objects, while character streams only handle characters or strings, byte stream provides the ability to handle any type of IO operation, but it cannot directly handle Unicode characters, and the character stream can be;

File operations (character stream write operations)
1. Create an object of the FileWriter class and associate the file
/*
* Note: One: The characteristics of the associated file: if it does not exist before, the program will automatically create one, if the existence will be used directly, but will overwrite the contents of the file before the
* Note: Two: If you write only the name of the file, do not write the specific path, the default path is the current project.
* Note: Three: We can specify the path ourselves, but make sure the path exists. Otherwise, the exception is reported: Filenotfoundexception:q:\temp1.txt (the system cannot find the path specified.) )
*/
FileWriter FileWriter = new FileWriter ("test");

2. Call the method that writes data from memory to disk
Note Four: When the Write method is executed, the data is temporarily placed in the inner array of the stream object, which is an array of bytes that will default to the encoding table
Filewriter.write ("Bingbingbang");

3. Refresh-Flushes the in-memory content from memory to disk
Filewriter.flush ();

4. Close stream--two functions: A: Turn off stream B: Refresh
Fifth Note: The stream object must be closed after it has been used, or it cannot be read or written if the subsequent program opens the stream.
Filewriter.close ();
Sixth note: When the Stream object is closed, no further action is made, otherwise an exception is reported: Stream closed

5. character file continuation
Filwriter fileWriter = new Filewirter ("D:\\test", append:true);

Read operation
1. Create an object of the FileReader class and associate the file (throws an exception when the file does not exist FileNotFoundException)
2. Call the method that reads the data into memory

* Two kinds of reading methods
* Read () One-to-one reading ... Slow in English: read out the pointer (cursor) after a character, the pointer (cursor) to move back one, when read out as-1 indicates that the read is complete
* Read (byte[]) can read more than one character at a time, the number of read characters stored in the array, its return value is the number of characters read,-1 indicates that the read is complete


Character Buffer stream
* Character Buffer stream: (character buffer)
* Definition: In order to improve the ability of reading and writing, there is no ability to read and write, you must use the character stream to read and write.
*
* The buffer stream can be likened to a catalyst or a high speed trolley
* Buffered flow is a typical decorative design pattern
* Character Buffer stream classification:
* Character Buffer read stream: BufferedReader no ability to read
* Character Buffer write-out stream: BufferedWriter does not have the ability to write
Instance:
Write operations

        Create a character to write out the stream fileWriter FileWriter = new FileWriter ("test");//write out BufferedWriter BufferedWriter = new using the character buffer stream implementation BufferedWriter (fileWriter);//write Operation Bufferedwriter.write ("asdf");//bufferedwriter.write ("\ r \ n");// Line break Bufferedwriter.newline () under Windows,//newline, can achieve cross-platform        

  

Read operation

A: read one character at a time int num;while (num = Bufferedreader.read ())! =-1) {System.out.print ((char) num);} B: Read multiple characters at a time char[] arr = new Char[2];while (num = Bufferedreader.read (arr))! =-1) {System.out.print (new String (arr,0,num ));} C: read one line at a time  readLine ()//principle: A character read a character until it reads the newline character. Then return all the read characters//Note points: The current line break is not returned; The return value is what we read. If it's done, Returns nullstring data = Null;while ((data = Bufferedreader.readline ()) = null) {System.out.print (data); System.out.println ();//newline}

  

BYTE stream

* Byte stream: bytes are transmitted, any type of data can be transmitted
* Byte output stream outputstream
* Byte input stream InputStream
* Byte buffered output stream Bufferedoutputstream
* Byte buffer input stream Bufferedinputstream
*

Byte stream write FileOutputStream FileOutputStream = new FileOutputStream ("D:\\filewrite.txt");//Because the byte stream used cannot be used directly by the character, Need to encode fileoutputstream.write ("FileWrite". GetBytes ());//byte stream read-in (single read) FileInputStream FileInputStream = new FileInput        Stream ("D:\\filewrite.txt");//Because the byte stream used is not directly using the character, it needs to be encoded int num = 0;        while (num = Fileinputstream.read ())! =-1) {System.out.print (char) num); }//byte stream read in (read in array) FileInputStream FileInputStream = new FileInputStream ("D:\\filewrite.txt");//Because the byte stream used is not directly using the character, it needs to go into        Line encoding byte [] bs = new byte[3];        while ((Fileinputstream.read (BS))! =-1) {System.out.print (new String (BS)); }//inputstream available () method gets the number of file bytes FileInputStream FileInputStream = new FileInputStream ("D:\\filewrite.txt");//AS        The byte number of the fruit is not recommended using byte [] bs = new byte[fileinputstream.available ()];        while ((Fileinputstream.read (BS))! =-1) {System.out.println (new String (BS)); }

  


Standard input/output stream
receiving data from the keyboard (input source) into memory
You can directly get the standard input stream object, which is already bound to the input source, which means you can enter data directly from the keyboard.
TIP: The standard input stream is a byte stream
InputStream InputStream = system.in;
Inputstream.read () is a blocking method that waits for the user's input
int num = Inputstream.read ();

---------------------------------------------------------------------------------------------------

* Conversion stream: Stream from bytes to character streams
* Byte-by-character decoding
* Character-by-byte encoding
* To let the character Buffer stream ReadLine () NewLine () and other services to the byte stream
* InputStreamReader Input Conversion stream
* OutputStreamWriter Output Conversion stream

BufferedReader keyboardasinput = new BufferedReader (new InputStreamReader (system.in)); BufferedWriter consoleasoutput = new BufferedWriter (new OutputStreamWriter (System.out)); BufferedReader fileasinput = new BufferedReader (New FileReader ("D:\\test")); BufferedWriter fileasoutput = new BufferedWriter (New FileWriter ("D:\\testok", true));//Can be appended

  


/**
* Replace the input source output source
* Originally from the keyboard input, changed from file input
* Originally from the console output, changed from file output
*/

System.setin (New FileInputStream ("D:\\test")); System.setout (New PrintStream ("D:\\testok")); BufferedReader keyboardasinput = new BufferedReader (new InputStreamReader (system.in)); BufferedWriter consoleasoutput = new BufferedWriter (new OutputStreamWriter (System.out));


/**
* File class. Used to manipulate files and paths
*
* Create a file
* Create path
* Multi-path creation
*
* Determine if it is a file
* Determine if it is a path
* Determine if hidden
*
* Get Path
* Get files or folders in the specified directory
* Get file List
*
* Two ways to create a file object
* Through full path implementation
* Via new File (parent directory, subdirectory)
* Via new file (parent directory), subdirectory)
*/

* Byte print stream: PrintStream features print functionality in addition to the output stream
* Character Print stream: PrintWriter
*
*
* PrintStreamThe constructor method accepts parameters
* 1, String path
* 2,file Object
* 3,outputstream
*
* The normal write method needs to call the flush or Close method to see the data.
* After JDK1.5, Java extended the PrintStream, adding formatted output, and using the printf () overloaded method to format the output directly.
* However, when formatting the output, you need to specify the format of the output data type. %d,%s,%f,%LF,%c
*
* bytes of print stream supported devices:
* 1.File type of File
* 2. String type of File
* 3. Byte output stream
*
* PrintStream in practice mainly has the following two uses
* 1, the arbitrary type of data automatically converted to a string output, quite convenient.
* 2, easy to collect abnormal log.
* System.out is a PrintStream object maintained within the System
*
* Print exception to file PrintStream Logprintstream = new PrintStream (new FileOutputStream (LogFile, true));
*
*
* PrintWriter
* 1, string path.
* 2,file object.
* You can also specify an encoding table for data of type. That is, the character set.
* 3,outputstream
* 4,writer
* For 3,4 types of data, you can specify automatic refresh.
* Note: When this auto-refresh value is true, only three methods can be used: Println,printf,format.
* If you want to have both automatic refresh and encoding. How do I wrap a stream object?
* Printwrter pw = newPrintWriter(NewOutputStreamWriter(NewFileOutputStream("A.txt"), "Utf-8"), true);
* If you want to improve efficiency. You also use the Print method.
* PrintWriter pw = newPrintWriter(NewBufferedWriter(NewOutputStreamWriter(NewFileOutputStream("A.txt"), "Utf-8"), true);

Javase Second study essay (iv)

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.