20145326 Java Programming 6th Week of study summary

Source: Internet
Author: User
Tags java se

20145326 "Java Program Design" The 6th Week study summary textbook Learning content Summary

Tenth Chapter

First, the use of InputStream and OutputStream

1. Concept of stream design

To use the input/output API, it is important to understand how to abstract input/output concepts in Java, as well as InputStream, OutputStream inheritance architectures. This allows for consistent operation regardless of standard input/output, document Input/output, network input/output, and database input/output. Java abstracts the input/output into streams, the source and destination of the data, the convergence of the two is a stream object, in fact, the data is like water, the stream is like a pipe, through the connection of water pipe, the flow from one end to the other end. This metaphor is very figurative! From an application perspective, if you want to take the data out of the source, you can use the input stream, and if you want to write the data to the destination, you can use the output stream. In Java, the input stream represents the object as an Java.io.InputStream instance, and the output stream represents the object as an Java.io.OutputStream instance. How do I write a program without knowing the source and destination? A common dump () method can be designed.

The dump () method accepts instances of InputStream and OutputStream, respectively, representing the source of the data being read and the destination of the output data. In the event of an error in InputStream and OutputStream related operations, Throws a Java.io.IOException exception, which is not handled here specifically, but is declared throws on the dump () method, handled by the client calling the dump () method. When you do not use InputStream and outputstream, you must use the close () method to close the stream. Because InputStream and OutputStream operate the Java.io.Closeable interface, whose parent interface is the Java.lang.AutoCloseable interface, you can use JDK7 to try to automatically turn off resource syntax. Each time the data read from InputStream is placed into a byte array, the InputStream read () method attempts to read the data in byte array length and returns the bytes actually read, as long as it is not-1, which means that the data is read. You can use the write () method of OutputStream to specify the byte array to write out, the initial index, and the length of the data. Although the book is not formally introduced to the network program design, but the use of Java.net.URL is very simple, as long as the specified URL, the URL instance will automatically make the HTTP protocol, you can use the OpenStream method to obtain the InputStream instance, representing the data stream connected to the site.

2. Streaming Inheritance Architecture

Remember System.in and System.out? If you look at the API files, they are instances of InputStream and PrintStream, respectively, representing standard input and standard output, which, in the case of a personal computer, usually corresponds to input and output in text mode. You can use the Setin () method of the system to specify the InputStream instance and re-specify the standard input source.

You can also use the system's SetOut () method to specify the PrintStream instance, outputting the result to the specified destination.

In this example with PrintStream packaging FileOutputStream, you operate PrintStream related methods, PrintStream will operate FileOutputStream for you. In addition to system.in and System.out, there is a system.err for the PrintStream instance, called the standard error input stream, which is used to immediately display the error message.

3.FileInputStream and FileOutputStream

FileInputStream is a subclass of InputStream, you can specify the file name creation instance, once the document is created to open, then can be used to read the data, FileOutputStream is a subclass of OutputStream, you can specify the file name creation instance, Once the document is created, it can then be used to write data, whether FileInputStream or FileOutputStream, closing the document with close () when not in use.

4.ByteArrayInputStream and Bytearrayoutputstream

Bytearrayinputstream is a subclass of InputStream, and you can specify a byte array to create an instance. Once created, you can read a byte array as a data source. Bytearrayoutputstream is a subclass of OutputStream, and you can specify a byte array to create an instance. Once created, the byte array can be written as a destination for writing data.

5. Stream Processing Adorner

InputStream, OutputStream provides streaming basic operations, and if you want to do processing for input/output data, you can use a wrapper class. The previously demonstrated scanner class is as a packager, which accepts InputStream instances, you manipulate scanner packager-related methods, scanner actually manipulate the packaged inputstream to get the data and convert it to the type of data you want. Some subclasses of InputStream and OutputStream also have the role of packager. The printstream described above is a practical example, you manipulate PrintStream's print (), println () and other methods, PrintStream will automatically convert to byte array data, using packaged outputstream for output. Here are a few common types of stream decorators.

The first is Bufferedinputstream and Bufferedoutputstream, both of which have buffering effects. If InputStream can read enough data to the memory buffer at the first read (), the subsequent call to read () will see if the buffer has data, and if it reads from the buffer, it does not read the data from the source to the buffer, thus reducing the number of times the data is read directly from the source. will be helpful for reading efficiency. After all, memory access is faster. If OutputStream writes data to an in-memory buffer every time it is written (), the buffer is full and then writes the buffer's data to the destination, which reduces the number of writes to the destination, which can be useful for write efficiency.

The second is that DataInputStream and Dataoutputstream,datainputstream and DataOutputStream provide methods for reading and writing Java basic data types, such as reading and writing int, double, Boolean, and so on. These methods are automatically converted between the specified type and bytes.

The third is that ObjectInputStream and Objectoutputstream,objectinputstream and ObjectOutputStream can store objects in memory and then read them back into objects. ObjectInputStream provides the ReadObject () method to read the data into an object, and ObjectOutputStream provides the WriteObject () method to write the object to the destination, which can be handled by both methods. The Java.io.Serializable interface must be manipulated, and the interface does not define any method, just as an indication that the object can be serialized. If some of the data members in the object do not want to be written out when the object is serialized, the transient keyword can be labeled.

Second, character processing class

1.Reader and writer Inheritance architecture

For reading character data, Java SE provides the Java.io.Reader class, which abstracts the source of the character data read-in, and writes to the character data, providing the Java.io.Writer class, which abstracts the destination of the data written out. When you are not using reader and writer, you must use the close () method to close the stream. Reader and writer manipulate the Closeable interface, whose parent interface is the Autocloseable interface, so you can use JDK7 to try to automatically turn off resource syntax. StringReader can be packaged as a read source, StringWriter can be used as a write destination, and finally a string of all written characters is obtained with ToString (). When you start the JVM, you can use-dfile.encoding to specify the encoding used by the FileReader, FileWriter.

2. Character processing Adorner

If the stream processing of the byte data, actually represents some characters of encoded data, and you want to convert these byte data to the corresponding encoded characters, you can use InputStreamReader, OutputStreamWriter to package streaming data, When InputStreamReader and OutputStreamWriter are established, the encoding can be specified, and if no encoding is specified, the character conversion is done with the default encoding obtained when the JVM starts. PrintStream is very similar to printwriter use, but in addition to OutputStream packaging, PrintWriter can also package writers, provide print (), println (), Methods such as format ().

11th Chapter

One, thread

1. Introduction to Threading

The various examples that have been introduced so far are single-threaded programs, that is, starting a program from the main () program entry point to the end of only one process, sometimes need to design programs can have multiple processes, known as multi-threaded programs.

The result is:

In Java, if you want to design a process independently of main (), you can compose a class operation Java.lang.Runnable interface, where the entry point of the process is operation in the run () method, for example

The result is:

In this program, the main thread executes the process defined in main (), the process defined by main () establishes the Tortoisethread and harethread two threads, the two lines routines respectively execute the process defined by the Tortoise and Hare Run (), To start the thread execution of the specified process, you must call the start () method of the thread instance.

The result is:

2.Thread and Runnable

From an abstract point of view and a developer's point of view, the JVM is a virtual machine that installs only a CPU called the main thread, which executes the execution flow defined by main (). If you want to add a CPU to the JVM, that is to create a thread instance, to start the extra CPU is to invoke the start () method of the thread instance, and the additional CPU execution process entry point can be defined in the run () method of the Runnable interface. In addition to defining the process in the runnable run () method, another way to compose a multithreaded procedure is to inherit the thread class and redefine the run () method. The advantage of manipulating the runnable interface is that it is more resilient, and your class has the opportunity to inherit other classes. If the thread is inherited, then the class is a thread, usually in order to directly take advantage of some of the methods defined in thread to inherit the thread.

3. Thread Life cycle

Daemon Threads: The main thread starts execution from the main () method until the end of the main () method stops the JVM. If additional threads are started in the main thread, the default is to wait for all threads that are started to execute the run () method before aborting the JVM. If a thread is marked as a daemon thread, the JVM terminates automatically at the end of all non-daemon threads. Starting with the main () method is a non-daemon thread, and you can use the Setdaemon () method to set whether a thread is a daemon thread. You can also use the Isdaemon () method to determine whether a thread is a daemon thread.

Thread basic state diagram: After invoking the thread instance start () method, the basic state is executable (Runnable), blocked (Blocked), in-Execution (Running). After instantiating the thread and executing the start () method, the thread enters the runnable state, at which point the thread has not really started executing the run () method and must wait for the queue to be queued to the CPU to execute, and the thread executes the run () method into the running state, and the thread looks like it is executing simultaneously , but in fact, at the same point in time, a CPU can only execute one thread, but the CPU will constantly switch threads, and the switch moves quickly, so it looks like it is executing simultaneously. The thread has priority, and the SetPriority () method of thread can be used to set priority. The minimum value is 1, the maximum value is 10, and the default is 5. The higher the number, the higher the priority, the more priority the shift is to the CPU, and if the priority is the same, the output is executed. With multi-threading, when a thread enters the blocked, it is often one of the ways to improve performance by letting another line run into the CPU to avoid CPU idle.

Placement thread: If a thread is running and a B thread is allowed to join in the process, and the B thread executes before continuing the A-thread process, you can use the join () method to complete the requirement.

Sometimes the thread that joins may be too long, you don't want to wait indefinitely for the thread to finish, you can specify a time at join (), such as join (10000), which means that the thread that joins the process can handle up to 10000 milliseconds, or 10 seconds, if the joined thread is not finished, Just ignore it.

Stop thread: After the thread finishes the run () method, it enters dead, and the thread that enters dead (or has already called the Start () method) cannot call the start () method again, or it throws an error. Thread's resume (), suspend (), destroy () are not recommended for use.

4. About Threadgroup

Each thread belongs to a line Cheng group, and if it is not specified, it is classified into the line Cheng group that produces the child thread, or you can specify the line Cheng group yourself, and the thread cannot be replaced once it has been grouped into a group. Some methods of Threadgroup can make a difference to all threads in a group. If you want to get all the threads in the group at once, you can use the enumerate () method. The Activecount () method gets the number of threads for the group.

5.synchronized and volatile

When a thread accesses the same object resource, it causes a race condition, which we call a class that does not have thread safety. Each object will have an internal lock, or a monitoring lock, and the block labeled synchronized will be monitored, and any thread executing the synchronized block must first obtain the specified object lock. Java synchronized provides the ability to re-enter the synchronization, that is, when the thread obtains an object lock, if the execution of the synchronized, the object to try to obtain the lock is the same source, you can directly execute. Synchronized required to achieve the mutex and visibility of the marked chunks. In Java, for visibility requirements, you can use volatile to reach the range of variables. Declaring volatile on a variable indicates that the variable is unstable and volatile. That is, it is possible to access in multi-threaded, which guarantees the visibility of variables, that is, if the thread changes the value of the variable, another thread must see the change. Variables marked as volatile do not allow thread cache, and the access to variable values must be in shared memory.

6. Wait and notice

Wait (), notify (), Notifyall () are the methods defined by the object, which can be used to control whether the thread frees the lock on the object or notifies the thread to participate in the lock contention. If you call the Wait () method of the locked object, the thread frees the object lock and enters the object waiting set to be blocked, and the other thread can compete for the object lock, and the thread that obtains the lock can execute the synchronized scope of the program code. The thread waiting on the collection does not participate in CPU scheduling, and wait () can specify the wait time until the thread joins the schedule again. If you specify a time of 0 or unspecified, the thread waits until it is interrupted (called interrupt ()) or informs (notify ()) that it can participate in the scheduling.

Second, parallel API

1.Lock, Readwriter and condition

If you need a thread pool, read-write locks and other advanced operations. The Java.util.concurrent package is provided after JDK5 to build a more robust parallel application based on the API. The Java.util.concurrent.looks package provides lock, readwriter and condition interfaces as well as related operation classes, which can provide similar synchronized, wait (), notify (), The role of Notifyall () and more advanced features. Use Lock:lock interface One of the main operation class is Reentrantlock, can achieve synchronized function. The lock interface also defines the Trylock () method, which returns true if the thread calls Trylock () to obtain a lock, and returns False if the lock cannot be taken, and then resolves the deadlock problem. Use Readwriter: If there are two threads that want to call get () with the size () method, because a locked relationship, where one thread can only wait for another thread to unlock, it is not possible for two threads to call the Get () with the size () method at the same time, however both methods simply read the object state, There is no change to the object state, and if it is just a read operation that allows the thread to parallel concurrently, the read efficiency will improve. The Readwriter interface defines a read lock and write lock, which can be used to return a lock operand using the Readlock (), Writelock () method.

Use Stampedlock:readwritelock to obtain a write lock when there is no read or write lock. This can be used to implement pessimistic reads. The Stampedlock class has been added to JDK8 to support optimistic reading. In other words, if you read a lot of threads and few write threads, you can be optimistic that there is very little chance of writing and reading occurring at the same time, so it is not pessimistic to use a full read lock, and the program can see if the data is read, whether it is being changed by the write thread, and then take the next steps.

Use the Condition:condition interface to match the lock. Calling condition's await () will cause the thread to enter the condition waiting set, and to notify a thread waiting in the collection, you can call the signal () method and use the Signalall () method if you want to notify all threads waiting in the collection. The await (), signal (), Signalall () methods of the condition are considered to correspond to the wait (), notify (), and Notifyall () methods of object.

2. Using executor

Runnable is used to define executable processes and data that can be used, and thread is used to perform runnable. Starting with JDK5, the Java.util.concurrent.Executor interface is defined to separate the runnable designation from the actual execution.

In the Java SE API, the behavior of a service like the thread pool is actually defined in the executor subinterface java.util.concurrent.ExecutorService. If you need the functionality of the thread pool, you can use Java.util.concurrent.ThreadPoolExecutor. Depending on the needs of the different thread pools, Threadpoolexecutor has several different constructors to use. The shutdown () method of the Executorservice will close the executorservice when the specified execution runnable is complete, and the other Shutdownnow () method can immediately close executorservice. Runnable objects that have not yet been executed are returned as list. The future is often used in conjunction with callable, and the callable function is similar to runnable, allowing you to define the process you want to perform, but the runnable run () method cannot return a value or throw a check exception. However, the call () method of callable can return a value, or it can throw a check exception. Scheduledexecutorservice is a executorservice sub-interface, as the name implies, allows you to work scheduling. The Schedule () method is used to schedule how long the runnable or callable instance is delayed and to return an instance of the future sub-interface scheduledfuture. Another operation class of the future Java.util.concurrent.ForkJoinTask and its subclasses as long as the purpose is to solve the problem of divide and conquer. The so-called divide and conquer problem, refers to these problems, can be decomposed into sub-problems of the same nature, sub-problems can be decomposed into smaller sub-problems, the same nature of sub-problems to solve and collect the results of the operation, in a multiprocessor environment, each processor allocates a thread, each thread executes a sub-task, respectively. The difference between Forkjoinpool and other executorservice operations is that it implements the work-stealing calculus. Its established thread, if it completes the task at hand, will try to find and perform subtasks created by other tasks, keeping threads busy and effectively leveraging the processor's capabilities.

3. Introduction to Parallel collection

Copyonwritearraylist operates the list interface, as the name implies, when an instance of this class is written, a new array is created internally, the reference to the original array index is copied, and a write operation is made on the new array, and after the write is completed, the variables referencing the old array inside the original reference to the new array. For a scenario where a write operation is infrequent and frequent iterators are used, copyonwritearraylist can be used to improve the efficiency of the iterator operation. Blockingqueue is the sub-interface of the queue, the new definition of put () and take (), and so on, the line Chengjo call put () method, the queue is full, the case will be blocked, the line Chengjo call the Take () method, in the case of empty queue is blocked. Concurrentmap is a sub-interface of map that defines methods such as putifabsent (), remove (), and replace (). These methods are atomic operations. Putifabsent () The key/value object is not placed in Concurrentmap when the key object is not present, otherwise the value object corresponding to the key is returned. Remove () removes the key/value object only if the key object exists and the corresponding value object is equal to the specified value object. Replace () has two versions, one of which is only in the presence of the key object, and the corresponding value object equals the specified value object, the value object is substituted, and the other version is the value object is substituted when the key object exists.

Problems in teaching materials learning and the solving process

Actually feel good, like Lou Teacher said, the No. 4567 chapter of the content is the Java core content, more abstract difficult to understand. After the content is to introduce the application of various APIs, are living examples, more specific, if it is difficult because of this part of the knowledge is unfamiliar, not familiar. You first clear the clue, and then read a few times more books, more than a few times to knock code. It feels like it's coming up! Should pay attention to the scientific study method ~ do not blindly!!!

The specific code has been fully managed, here will not repeat.

Problems in code debugging and the resolution process

I don't understand why the code on the 334 page of the book executes THREADB first. Later found that the main thread starts after the program starts, the main thread in the new threadb, and after starting THREADB, will be added to the main process flow, so threadb will be executed first, and then the main thread will continue the original process.

The results of the final operation are as follows:

Other (sentiment, thinking, etc., optional)

Although this week is self-taught two chapters, more knowledge points, but fortunately, nothing difficult, like Lou teacher said before, Java's core knowledge and difficulties have been learned, the following chapters are all introduced some of the application of the class. Look at the first time the textbook must feel strange, difficult to accept. It's a process, it's normal. In the continuous learning, I also constantly looking for their own good learning methods. Look at the first time the textbook just want to have a general understanding, the mind sketched out a contour. And then see the second time is gradually understanding and experience, to the outline of the content, then can not only read, but also to combine the code on the book, I also have to take the initiative to tap the Code, the initiative to find the problem. The third time is to comb the knowledge point is also a memory, the brain and knowledge fusion. This way down to the knowledge will definitely have further control! There will be a qualitative leap in itself! To learn to grasp the focus, the strength of the blade, to find fun, maintain passion, improve learning efficiency! I read the textbook with purpose, not blindly. I later found this particularly important! I know the tenth and 11th chapters also introduce some of the applications of the class, so I took the same approach as last week, while reading, while summing up, reading a total of how many APIs, each API architecture is what, each API's role and considerations are what. In this way there is a systematic study, the sense of efficiency is very high! And the mind is clear. In fact, this knowledge is not difficult, we just feel strange. Students have fear mood and weariness, of course not to go in, but also talk about what efficiency! The knowledge of these two chapters is not as abstract and difficult to understand as the previous objects, encapsulation, inheritance of those basic concepts, are living concrete examples, the acceptance is actually quite fast. Lou teacher said is very right, the important thing is not to learn how much Java knowledge, but through continuous learning process, to summarize a set of suitable for their own good learning methods, which will be useful for a lifetime. Of course, different people are certain that the situation is not the same, suitable for their own is the best. My biggest harvest this week is to really realize that learning should also speak science, not blind. Time is used much, not necessarily to learn well. Find your own learning methods to improve efficiency! This is more important than everything! Adjust your own mentality, any thing do not have fear mood, everything beginning difficult, as long as is right, insist! Will certainly benefit from the end!!!

Learning progress Bar
Lines of code (new/cumulative) Blog volume (Add/accumulate) Learning time (new/cumulative) Important growth
Goal 3500 rows 20 articles 300 hours
First week 120/120 1/1 14/14
Second week 340/460 1/2 14/28
Third week 200/660 1/3 14/42
Week Four 320/980 1/4 14/56
Week Five 280/1260 1/5 14/70
Week Six 478/1738 1/6 16/86

20145326 Java Programming 6th Week of study summary

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.