Multithreading
Process-to-thread differences: processes need to allocate separate memory space, threads work in the same memory space, and can share the same block of memory and system resources
Java-related APIs:
1) Thread class
Method: Start (), Urn (), getName () Get line name, SetName () Change line name, SetPriority () Set priority, Setdaemon () daemon thread; join () wait; Interupt () Middle this thread;
IsAlive () Determines whether the operation is still in the life cycle; yield () static, stopping the thread from running;
2) Runnable Class (Public specification)
3) Object class
Method: Wait () waits; notify () wakes up thread; Notifyall () Wakes all threads
Creation of Threads:
1) inherit the thread class
Step: A, create a class that inherits the thread class
B. Rewrite the Run () method in the subclass to write the code that you want to run
C. Create an instance of the thread class
D. Call the Start () method on the instance to start running the thread
2) Implement Runnable interface
Step: A, create a class to implement the Runnable interface
B, within the run () method specified by runnable, write the code that you want to run
C. Create an instance of the Runnable class
D. Create a thread object and pass the instance of Runnable as the constructor parameter
E, call the Start () method of an instance of the thread class
Thread priority is between: 1--10, thread run order is determined by priority, setpriority () sets thread priority, GetPriority () takes thread priority
Thread synchronization (Mutex):
Function: Locking the object (monitor), that is, when this thread is started, other threads cannot use the
Synchronization block Format: Synchronized (the object that acquired the lock) {//code to lock}
Deadlock: cannot be run after release, need to consider priority release
The life cycle of a thread:
Java threads are generated by instantiation, or because the run () program finishes running, the thread may hibernate (sleep), yield, or wait for other threads to run.
A thread in the runnable state is given a different priority, and the JVM decides to enter the Runing state, and the same thread will return to the runnable state because it calls the yield () method itself. The sleep () method is also called in the runing state
While entering the state of blocking (blocked), waiting until the end of the thread's hibernation and returning to the runnable state, the thread in the Rining state may have to go into blocking because another thread called the Join () method
State, the original thread will wait until the thread that is started has finished running, and the original thread will enter the runnable state again and wait for the run
Fix the state diagram of the thread:
First: The thread could not be in a runing state because it could not get an object lock on an object, which would let the thread be thrown into the lock pool of the object by Runing's state, and wait for the object lock to be acquired, if the object lock has been released. Then a thread in the lock pool enters the runnable state to wait for it to run, and the original thread will not run if the thread that gets the object lock waits for the object lock to be taken by another thread.
Second time:
Java I/O system
I: is input for inputs; O: output for outputs
Flow ( is the abstraction and foundation of I/O )
Category: 1) According to the direction of:
Input stream: Reading data from a data source to a program
Output stream: The destination where data is written from the program to the data
2) divided by unit:
BYTE stream: The memory variable type is bytes ()
1 package Com.lovo; 2 3 Import Java.io.File; 4 Import Java.io.FileInputStream; 5 Import java.io.FileNotFoundException; 6 Import Java.io.FileOutputStream; 7 Import java.io.IOException; 8 Import Java.io.InputStream; 9 Import java.io.outputstream;10 11/**12 * Bytes Input/output stream Test * * @author Xiao Ming *16 */17 public class Iotest {p Ublic static void Main (string[] args) {StringBuffer buffer = new StringBuffer ();//String Buffer 21 22 /* Input stream */23 InputStream in = null;24 try {26//1. Open input stream in = new FILEINPUTST Ream ("E:\\jg\\exercise.txt"); 28//2. Read//byte[] b = new Byte[128];30 byte[] b = new byte[1024 * 4];31 int len = In.read ( b); Returns the number of bytes read to, and returns 1 for reading to the end of the stream (len! =-1) {Buffer.append (new String (b, 0, Len)); BYTE parsing to string append to buffer len = In.read (b);}36//System.out.println ("read" + len + "bytes(Buffer.tostring ()), System.out.println (FileNotFoundException e), and. Printstacktrace (); \ n} catch (IOException e) {43 e.printstacktrace (); 3. Release the resource, close the input stream if (in! = null) {try {in.close ()}; CA TCH (IOException e) {e.printstacktrace (); 49}50}51}52 53/* Output stream */54 outputstream out = null;55. try {File File = new file ("D: \\test\\demo\\test.txt "); if (!file.getparentfile (). exists ()) {//file path does not exist, create all directories that do not exist in the path F Ile.getparentfile (). Mkdirs (); 60}61//1. Open output Stream fileoutputstream = new (file); 63//2. Write Out.write (Buffer.tostring (). GetBytes ()); catch (FileNotFoundException e) {$ E. Printstacktrace (); IOException} catch (e) {e.printstacktrace (); n} finally {70 3. Releases the output stream resource, if (out! = null) {try {out.flush (); Ut.close (); IOException} catch (e) {e.printstacktrace (); 77}78 }79}80}81}
Character stream: The memory variable type is char ();
1 package Com.lovo; 2 3 Import java.io.FileNotFoundException; 4 Import Java.io.FileReader; 5 Import Java.io.FileWriter; 6 Import java.io.IOException; 7 Import Java.io.Reader; 8 Import Java.io.Writer; 9 10/**11 * Character input/output stream Test * * @author xiaoming *15 */16 public class IOTest2 {+-public static void main (string[ ] args) {StringBuffer buffer = new StringBuffer (); 20 21/* Input stream */22 Reader reader = null;23 24 try {25//1. Open stream-reader = new FileReader ("E:\\jg\\exercise.txt"); 27//2. Read Take char[] ch = new char[128]; Buffer: int len;30 do {len = Reader.read (ch); if (len = =-1) Break;34 Buffer.append (New String (CH, 0, Len)), while (len! = 1); 3 6 System.out.println (buffer.tostring ()); PNs} catch (FileNotFoundException e) {e.printst Acktrace (); 39} catch (IOException e) {e.printstacktrace (); (), and finally {42//3. Release Resources F (reader! = null) {Reader.close} catch (IOException e) {e.printstacktrace (); 48}49}50}51 52 */output stream */53 5 4 writer writer = null;55-try {57//1. Open stream. Writer = new FileWriter ("D:\\test . txt "); 59//2. Write Writer.write (buffer.tostring ()); catch (IOException e) {e.printstacktrace (); 63 } finally {64//3. Release resource, if (writer! = null) {$ try {67 Writer.flush (); Writer.close (); catch (IOException e) {70 E.printstacktrace (); 71}72}73}74}75}
File class:
File class: Provides the basic functionality to manage disk files and directories, a file object that represents the name and location of a document or directory string
1 package Com.lovo; 2 3 Import Java.io.File; 4 Import Java.io.FileInputStream; 5 Import java.io.FileNotFoundException; 6 Import Java.io.FileOutputStream; 7 Import java.io.IOException; 8 Import Java.io.InputStream; 9 Import java.io.outputstream;10 11/**12 * Bytes Input/output stream Test * * @author Xiao Ming *16 */17 public class Iotest {p Ublic static void Main (string[] args) {StringBuffer buffer = new StringBuffer ();//String Buffer 21 22 /* Input stream */23 InputStream in = null;24 try {26//1. Open input stream in = new FILEINPUTST Ream ("E:\\jg\\exercise.txt"); 28//2. Read//byte[] b = new Byte[128];30 byte[] b = new byte[1024 * 4];31 int len = In.read ( b); Returns the number of bytes read to, and returns 1 for reading to the end of the stream (len! =-1) {Buffer.append (new String (b, 0, Len)); BYTE parsing to string append to buffer len = In.read (b);}36//System.out.println ("read" + len + "bytes(Buffer.tostring ()), System.out.println (FileNotFoundException e), and. Printstacktrace (); \ n} catch (IOException e) {43 e.printstacktrace (); 3. Release the resource, close the input stream if (in! = null) {try {in.close ()}; CA TCH (IOException e) {e.printstacktrace (); 49}50}51}52 53/* Output stream */54 outputstream out = null;55. try {File File = new file ("D: \\test\\demo\\test.txt "); if (!file.getparentfile (). exists ()) {//file path does not exist, create all directories that do not exist in the path F Ile.getparentfile (). Mkdirs (); 60}61//1. Open output Stream fileoutputstream = new (file); 63//2. Write Out.write (Buffer.tostring (). GetBytes ()); catch (FileNotFoundException e) {$ E. Printstacktrace (); IOException} catch (e) {e.printstacktrace (); n} finally {70 3. Releases the output stream resource, if (out! = null) {try {out.flush (); Ut.close (); IOException} catch (e) {e.printstacktrace (); 77}78 }79}80}81}
Advanced byte Stream Classification:
1) Filter Flow: (both FileInputStream and FileOutputStream subclasses)
Category: Buffered streams: Bufferedfileinputstream and Bufferedoutputstream
Data flow: Dateinputstream and Dateoutputstream
Count: Linenumberinputstream (indicates which line is being read)
Push back Data flow: Pushbackinputstream
Print Data flow: printstream (with refresh function)
2) Object flow: ObjectInputStream and ObjectOutputStream
3) Merger: Sequenceinputstream
Advanced Character Stream:
1) Buffered streams: BufferedReader and BufferedWriter
2) Conversion stream: InputStreamReader and OutputStreamWriter (byte-character)
3) Print output stream: PrintWriter
Object Flow:
Serialization: ObjectInputStream ("Panorama" that holds objects in memory) in order to implement object serialization, the corresponding class must implement the Java.io.Serializable interface
Deserialization: ObjectOutputStream
Property plus a transient modifier whose job is not serialized
Java Graphical user interface programming
AWT: Abstract window Toolbox to ensure platform independence, but heavily dependent on downlevel operating systems-weight components
Swing: With better platform independence and portability-lightweight components.
Component three elements: (content), (appearance display), (behavior)
Components three parts: models, views, controllers
Recognize several methods
Add (): Adds the component to the container.
RemoveAll (): Removes all components from the container.
Remove (Component c) Removes the component specified by the parameter in the container.
Validate (): This method is called whenever a container adds a new component or removes a component, ensuring that the components in the container are displayed correctly.
Heavyweight containers: jfram (Form), JDialog (dialog box), JWindow (window), JApplet (applet), inherited from Container container class
Swing Menu:
1/** 2 * Add Menu 3 * /4 public void AddMenu () {5 //menu bar 6 jmenubar JMenuBar = new JMenuBar (); 7 // Add a menu bar to the current form 8 This.setjmenubar (JMenuBar); 9 //Menu JMenu file = new JMenu ("files"); file), //submenu JMenu newFile = new JMenu ("new"), Newfile.add ("Java Project"), and Newfile.add (". NET project "), File.add (NewFile), and/ or sub-menu item JMenuItem Open = new JMenuItem (" Open ... "); (open), file.add ("Save"); File.add ("Save As"); get "Save" menu item JMenuItem save = File.getitem ( 2); save.setenabled (FALSE);//disable +// for the "Open" menu item, add the shortcut key to Open.setaccelerator ( Keystroke.getkeystroke (keyevent.vk_o,32 inputevent.ctrl_mask));
Layout:
1) Streaming layout manager: FlowLayout
2) Border layout Manager: BorderLayout
3) Grid Layout Manager: Griflayout (can pass two or four or no parameters)
4) Cassette layout manager: BoxLayout
1/** 2 * Add button 3 */4 public void AddButton () {5 6//Single line text box 7 JTextField text = n EW JTextField ("Please enter text"); 8 This.add (text, Borderlayout.north); 9 10/* Default Boundary layout manager */11//button JButton west = new JButton ("West"), JButton East = new JButton ("East"), JButton north = new JButton ("North"), JButton south = new JButton ("South"); 16 JButton Center = new JButton ("center"), 17////Add button//This.add (West, borderlayout.west); 19 This.add (east, Borderlayout.east);//This.add (North, Borderlayout.north), +//This.add (south, B Orderlayout.south//This.getcontentpane (). Add (center, Borderlayout.center); 23 24//Create Panel object 25 JPanel PNL = new JPanel (); 26 27/* Grid Layout manager */28 GridLayout layout = new GridLayout (3, 2, 10, 10); 2 9//This.setlayout (layout), 32//This.add (west); This.add (east), This.add//This.add (South);//This.add (center); 36 Pnl.setlayout (Layout), Pnl.add (west), Pnl.add (east), Pnl.add (north); 41 Pnl.add (south), Pnl.add (center), This.add (PNL, Borderlayout.center);
text boxes and Password boxes:
JTextField t=new JTextField ();
Jpassworfield j=new Jpassworfield ();
Layout management lets containers use method setlayout (layout objects) to design their own layouts
Events and Event sources:
Click the button: JButton in the text box, press ENTER: jtexfiled Select a new entry: JComboBox Check the entry: JList click check box: Jceckbox
Click the radio button: Jradiobutton select Menu bar: Jmenuttem move scroll bar: Jscroiibar, jslider about window action: Windows
Mouse action: Component move or drag: Component Key Press or Release: Component component Add or Remove: Container component move, restore, hide, display: Component
Event listeners, registering, and handling events:
Using the event delegate model to handle an event, the event source triggers an event, but the event source itself does not handle the event, but instead delegates the event to an object that is interested in handling it, and its object is called the event listener
Need to do: 1) Create a listener object that must correspond to an interface instance of the event listener (a type of event xxxevent, corresponding interface is Xxxlistener)
2) Register the Listener object on the event source (for Xxxevet registered as Addxxxlistener)
To define the Listener class:
1) define the listener in a separate class
2) Let the CUI program itself implement the Listener interface
3) using an internal class definition listener
4) Use the anonymous inner class to define the listener.
I/O systems, multi-threading, graphical user interface programming