IO: refers to the flow of data transfer between devices
Classification by flow direction:
Input stream
Output stream
Classification by data type:
Byte stream
A: Byte input stream
FileInputStream:
FileInputStream fis = new FileInputStream("file name of read data");
Byte buffered input stream: BufferedInputStream
Bufferedinputstream bis = new bufferedinputstream (New FileInputStream);
//Note: the file here must exist in advance
There are two ways to read data from byte input stream:
1. Read one byte at a time
int b = 0;
while((b=bis.read())!=-1){
System.out.print((char)b);
}
bis.close();
2. Read one byte array at a time
byte[] bytes = new byte[1024];
int length = 0;
while((length = bis.read(bytes))!=-1){
System.out.print(new String(bytes,0,length));
}
bis.close();
B: Byte output stream
FileOutputStream:
FileOutputStream fos = new FileOutputStream("write file name");
Byte buffered output stream: BufferedOutputStream
Bufferedoutputstream BOS = new bufferedoutputstream (New fileoutputstream);
//Note: the file here may not exist and will be automatically created later
How to write data:
1. Write one byte at a time
2. Write one byte array at a time
3. Write part of a byte array one at a time
Character stream (conversion stream) = byte stream + encoding table
A: Character input stream Reader
InputStreamReader:
Inputstreamreader ISR = new inputstreamreader (New FileInputStream);
Simplified writing: FileReader
FileReader fr = new FileReader("file name for reading data");
There are two ways to read data from ordinary character input stream:
1. Read one character at a time
int ch = 0;
while((ch = fr.read())!=-1){
System.out.print((char) ch);
}
fr.close();
2. Read one character array at a time
char[] chars = new char[1024];
int length = 0;
while((length = fr.read(chars))!=-1){
System.out.print(new String(chars,0,length));
}
fr.close();
Character buffered input stream: BufferedReader
BufferedReader br = new BufferedReader (New inputstreamreader (New FileInputStream);
BufferedReader br = new BufferedReader(new FileReader("file name for reading data");
The third way to read data from character stream: read one line at a time (readLine())
String s = null;
while((s = br.readLine())!=null){
System.out.print(s);
}
br.close();
B: Character output stream Writer
OutputStreamWriter:
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("write file name");
Simplified writing method: FileWriter
FileWriter fw = new FileWriter("write file name");
How to write data:
Write one character at a time
Write an array of characters one at a time
Write a part of a character array one at a time
Write one string at a time
Efficient stream, character buffered output stream: BufferedWriter
Bufferedwriter BW = new bufferedwriter (New outputstreamwriter (New fileoutputstream);
BufferedWriter bw = new BufferedWriter(new FileWriter("write file name");
Special data writing method of character stream:
newLine() writes a newline character. The newline character here is different according to different systems.
Byte input stream: InputStream (abstract class)
FileInputStream
Construction method of FileInputStream
FileInputStream(File file)
FileInputStream(String name)
There are two ways to read data from byte input stream:
Member method of FileInputStream
public int read()
public int read(byte[] b)
Read one byte at a time
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class FileInputStreamDemo1 { public static void main(String[] args) throws Exception { //1. Create byte input stream object //FileInputStream(File file) //When reading data, if the file does not exist, an error is reported File file = new File("a.txt"); FileOutputStream fos = new FileOutputStream(file); fos.write("sddd".getBytes()); FileInputStream fis = new FileInputStream(file);// (the system cannot find the specified file.) //Call the read method to read the data and output it on the console //public int read(), which can only read one byte at a time, returns the ASCII code value and casts the type int read = fis.read(); System.out.println((char) read); //If there is a lot of data in the file, it will be very troublesome to read one byte by one without any improvement //Improve reading using loops //Because we don't know when to finish reading the file data, we use the while loop //Controls what the conditions for jumping out of the while loop are, and the next byte of data. If it reaches the end of the file, - 1. //The first way to read data from byte input stream is the final version: int i=0; while ((i=fis.read())!=-1){ System.out.println((char) i); } fis.close(); fos.close(); } } Results (in the document): s d d d
The second way to read data from byte input stream: read one byte array at a time
public int read(byte[] b)
import java.io.FileInputStream; import java.io.FileNotFoundException; public class FileInputStreamDemo2 { public static void main(String[] args) throws Exception { //1. Create byte input stream object FileInputStream fis = new FileInputStream("a.txt"); //2. Read data //public int read(byte[] b) //Define a byte array // byte[] bytes = new byte[8]; // //Once this method is called, the bytes actually obtained are stored in the array, and the number of bytes actually read by the array is returned // int i = fis.read(bytes); // System.out.println(i); for(byte b:bytes){ System.out.print((char) b); } System.out.println("============="); String s = new String(bytes); System.out.println(s); // String s = new String(bytes, 0, i); // System.out.println(s); //Improve with cycle //The second way to read data from byte stream is the final code //The total number of bytes read into the buffer. If there is no more data, because the end of the file has reached, - 1. byte[] bytes = new byte[1024];//It is required to be 1024 or multiple of 1024 in the future int length=0; while ((length= fis.read(bytes))!=-1){ System.out.println(new String(bytes,0,length)); } } } Results (in the document): sddd
Copy the contents of a.txt in the current project directory to b.txt in the current project directory
Input stream
InputStream -- FileInputStream
Read one byte at a time
Read one byte array at a time
a.txt
Output stream
OutputStream -- FileOutputStream
Write values of type int one at a time
Write one byte array at a time
Write part of a byte array one at a time
b.txt
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class CopyFileDemo1 { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("b.txt"); // //2. Read data // //a: Read one byte at a time // int i=0; // while ((i= fis.read())!=-1){ // System.out.println(); // fos.write(i); // } //b: Read one byte array at a time byte[] bytes = new byte[1024]; int length=0; while ((length=fis.read(bytes))!=-1){ System.out.println(); fos.write(bytes,0,length); } fos.close(); fis.close(); } }
Put von Timo under the current project Copy JPG to the current directory and change the name to FTM jpg
Data source: from where
Von Timo jpg -- read data -- InputStream -- FileInputStream
Destination: where to go
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class CopyJpgDemo1 { public static void main(String[] args) throws Exception { //Create byte input stream object and byte output stream object FileInputStream fis = new FileInputStream("src\\Days23\\ftm.jpg"); FileOutputStream fos = new FileOutputStream("Feng Timo.jpg"); byte[] bytes = new byte[1024]; int length = 0; while ((length = fis.read(bytes)) != -1) { fos.write(bytes, 0, length); } fos.close(); fis.close(); } }
Buffer class (efficient class)
Byte buffered output stream
BufferedOutputStream
Byte buffered input stream
BufferedInputStream
import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; public class BufferedOutStreamDemo1 { public static void main(String[] args) throws Exception { //BufferedOutputStream(OutputStream out) //Create a new buffered output stream to write data to the specified underlying output stream. // FileOutputStream fos = new FileOutputStream("g.txt"); // BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c.txt")); bos.write("big data".getBytes()); bos.close(); } }
Byte buffered input stream
BufferedInputStream
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; public class BufferedInputStreamDemo1 { public static void main(String[] args) throws Exception { //BufferedInputStream //BufferedInputStream(InputStream in) //Create a BufferedInputStream and save its parameters. Input the stream in for later use. // FileInputStream fis = new FileInputStream("g.txt"); // BufferedInputStream bis = new BufferedInputStream(fis); BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c.txt")); // int i=0; // while ((i=bis.read())!=-1){ // System.out.println((char) i); // // } System.out.println("=========================="); byte[] bytes = new byte[1024]; int length=0; while ((length=bis.read(bytes))!=-1){ System.out.println(new String(bytes,0,length)); } bis.close(); } }
When the byte stream reads only one byte at a time, if the data is Chinese, symbols that we can't understand appear
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; public class BufferedInputStreamDemo2 { public static void main(String[] args) throws Exception { // When the byte stream reads only one byte at a time, if the data is Chinese, symbols that we can't understand appear BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c.txt")); int i=0; while ((i=bis.read())!=-1){ System.out.println((char) i); } } }This is because a Chinese character consists of three bytes. Only one byte can be read at a time
String(byte[] bytes, Charset charset)
Construct a new String and decode charset with the specified byte array. decode
byte[] getBytes(Charset charset)
Use the given charset to encode the String into a byte sequence and store the result in a new byte array. code
Coding: change what you can understand into what you can't understand, which is similar to encryption
String -- byte[]
Decoding: change what you can't understand into what you can understand, which is similar to decryption
byte[] -- String
public class StringDemo { public static void main(String[] args) throws Exception { String s = "Hello"; //String -- byte[] // byte[] bytes = s.getBytes("GBK"); // System.out.println(bytes); // printArray(bytes); byte[] bytes1 = s.getBytes("Unicode"); printArray(bytes1); System.out.println(); String s1 = new String(bytes1, "Unicode"); System.out.println(s1); } public static void printArray(byte[] bytes) { for (byte b : bytes) { System.out.println(b + ","); } } } result: -2, -1, 79, 96, 89, 125,
Character stream:
Character input stream
Reader
Character output stream
Writer
Writer
OutputStreamWriter: character output stream is a conversion stream obtained by adding byte stream and encoding table. When writing data later, it can be written according to the encoding specified by itself
public OutputStreamWriter(OutputStream out)
Create an OutputStreamWriter that uses the default character encoding. Convert character stream to byte stream by default
public OutputStreamWriter(OutputStream out,String charsetName)
According to the specified encoding, characters are used as a bridge to convert the data of byte stream into character stream
Convert byte stream to character stream
Character stream = byte stream + encoding table
import java.io.FileOutputStream; import java.io.OutputStreamWriter; public class OutputStreamWriterDemo1 { public static void main(String[] args) throws Exception { //1. Create character output stream object OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("aaa.txt"),"UTF-8"); osw.write("China"); osw.close(); //The coding table here should be consistent with the text, that is, UTF-8 } }
Reader
InputStreamReader: character input stream
public InputStreamReader(InputStream in)
Read the data and convert the data of byte stream into character stream with characters as a bridge according to the default encoding
public InputStreamReader(InputStream in,String charsetName)
Read the data and convert the data of byte stream into character stream with characters as a bridge according to the specified encoding
mport java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class InputStreamReaderDemo1 { public static void main(String[] args) throws Exception { InputStreamReader isr = new InputStreamReader(new FileInputStream("aaa.txt"), "UTF-8"); int i=0; while ((i= isr.read())!=-1){ System.out.println((char) i); } isr.close(); } } result: in country
Method for OutputStreamWriter to write data:
public void write(int c)
public void write(char[] cbuf)
public void write(char[] cbuf,int off,int len)
public void write(String str)
public void write(String str,int off,int len)
The difference between flush() and close():
1. After calling flush(), the stream object is not closed and can continue to write data.
2. After calling close(), the stream object is closed, and subsequent data cannot be written through this object.
import java.io.FileOutputStream; import java.io.OutputStreamWriter; public class OutputStreamWriteDemo2 { public static void main(String[] args) throws Exception { //1. Create character output stream object OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("bbb.txt")); //Write data //public void write(int c) writes a character osw.write(99); osw.write('a'); //After removing the close, we found that the data was not written to the file //reason //Files are actually bytes stored on the hard disk and need to be manually converted for storage //void flush() //Refresh the stream. // osw.flush(); //public void write(char[] cbuf) writes a character array char[] chars = {'a','b','c','d','e'}; osw.write(chars); //public void write(char[] cbuf,int off,int len) writes a part of the character array osw.write(chars,1,3); //public void write(String str) osw.write("Ming and Wang Zhenshuai"); //public void write(String str,int off,int len) writes part of a string osw.write("Ming and Wang Zhenshuai",3,2); osw.close(); } }
InputStreamReader: character input stream
Method of reading data:
public int read()
public int read(char[] cbuf)
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class InputStreamReaderDemo2 { public static void main(String[] args) throws Exception { //1. Create character input stream object InputStreamReader isr = new InputStreamReader(new FileInputStream("c.txt")); // int i = 0; // while ((i = isr.read()) != -1) { // System.out.println((char) i); // } //Read one character array at a time //The number of characters read is - 1 if it has reached the end of the stream char[] chars = new char[1024]; int length = 0; while ((length = isr.read(chars)) != -1) { System.out.print(new String(chars, 0, length)); } isr.close(); } }
Copy the contents of a.txt in the current project directory to b.txt in the current project directory
Data source:
a.txt -- read data -- character input stream -- Reader -- InputStreamReader
destination:
b.txt -- write data -- character output stream -- Writer -- OutputStreamWriter
import java.io.*; public class CopyFileDemo2 { public static void main(String[] args) throws Exception { //1. Create character input stream object and character output stream object InputStreamReader isr = new InputStreamReader(new FileInputStream("aaa.txt")); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("bbb.txt")); //Read and write data //The first way // int i =0; // while ((i= isr.read())!=-1){ // osw.write(i); // osw.flush(); // } char[] chars = new char[1024]; int length = 0; while ((length = isr.read(chars)) != -1) { osw.write(chars, 0, length); } osw.close(); isr.close(); } }
Since our common operations use the local default code, we basically do not specify the code when using it
However, I think the name of the character conversion stream object is a little long, so Java provides subclasses for us to use
Character stream = byte stream + encoding table
OutputStreamWriter = FileOutputStream + encoding table
InputStreamReader = FileInputStream + encoding table
Copy the contents of a.txt in the current project directory to b.txt in the current project directory
Data source:
a.txt -- read data -- character input stream -- Reader -- InputStreamReader -- FileReader
destination:
b.txt -- write data -- character output stream -- Writer -- OutputStreamWriter -- FileWriter
import java.io.*; public class CopyFileDemo3 { public static void main(String[] args) throws Exception { InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt")); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt")); // int i=0; // while ((i=isr.read())!=-1){ // osw.write(i); // osw.flush(); // } char[] chars = new char[1024]; int length=0; while ((length=isr.read(chars))!=-1){ osw.write(chars,0,length); } osw.close(); isr.close(); } }
In order to read and write efficiently, the character stream also provides the corresponding character buffer stream
Character buffered output stream: BufferedWriter
Character buffered input stream: BufferedReader
BufferedWriter:
Write text to the character output stream and buffer characters to provide efficient writing of individual characters, arrays and strings.
You can specify the buffer size, or you can accept the default size. The default value is large enough for most purposes.
BufferedWriter(Writer out)
Creates a buffered character output stream using an output buffer of the default size.
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class InputStreamReaderDemo1 { public static void main(String[] args) throws Exception { InputStreamReader isr = new InputStreamReader(new FileInputStream("aaa.txt"), "UTF-8"); int i=0; while ((i= isr.read())!=-1){ System.out.println((char) i); } isr.close(); } }
BufferedReader: character buffered input stream
Read text from the character input stream and buffer characters to provide efficient reading of characters, arrays and lines.
You can specify the buffer size, or you can use the default size. The default value is large enough for most purposes
BufferedReader(Reader in)
Creates a buffered character input stream that uses a default size input buffer.
public class BufferedReadDemo1 { public static void main(String[] args) throws Exception { // BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"))); BufferedReader br = new BufferedReader(new FileReader("a.txt")); //1. Read one character at a time // int i=0; // while ((i= br.read())!=-1){ // System.out.println((char) i); // } char[] chars=new char[1024]; int length=0; while ((length= br.read(chars))!=-1){ System.out.println(new String(chars,0,length)); } br.close(); } }
Put the BBB in the current project directory Txt content is copied to c.txt under the current project directory
Data source:
a.txt -- read data -- character input stream -- Reader -- InputStreamReader -- FileReader -- BufferedReader
destination:
b2.txt -- write data -- character output stream -- Writer -- OutputStreamWriter -- FileWriter -- BufferedWriter
import java.io.*; public class CopyFileDemo4 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("bbb.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("c.txt")); char[] chars = new char[1024]; int lenngth=0; while ((lenngth=br.read(chars))!=-1){ bw.write(chars,0,lenngth); } bw.close(); br.close(); } }
Special reading and writing methods of character buffer stream:
BufferedWriter:
void newLine()
Write a line separator. The line separator string is determined by the system property line Separator definition, not necessarily a single line break ('\ n') character.
BufferedReader:
public String readLine()
Read a line of text. A line is treated as a line feed ('\ n') and terminated by any one of the carriage return ('\ r') or subsequent line feeds.
import java.io.*; public class BuffereedDemo1 { public static void main(String[] args) { try { read(); } catch (Exception e) { e.printStackTrace(); } try { write(); } catch (Exception e) { e.printStackTrace(); } } public static void read() throws Exception { BufferedReader br = new BufferedReader(new FileReader("a.txt")); //public String readLine() reads one line of text at a time //The string containing the contents of the line, excluding any line termination characters. It is null if it has reached the end of the stream // String s = br.readLine(); // System.out.println(s); // String s1 = br.readLine(); // System.out.println(s1); //Read with loop String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } public static void write() throws Exception { BufferedWriter bw = new BufferedWriter(new FileWriter("a3.txt")); for (int i = 0; i <= 10; i++) { bw.write("big data" + i); bw.newLine(); } bw.close(); } }
Store the string data in the ArrayList collection into a text file
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class IOTest1 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); //Add elements to the collection list.add("hello"); list.add("world"); list.add("java"); list.add("bigdata"); BufferedWriter bw=null; try { bw = new BufferedWriter(new FileWriter("a4.txt")); for (String s:list){ bw.write(s); bw.newLine(); bw.flush(); } } catch (IOException e) { e.printStackTrace(); }finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
It is known that there is such a string in the s.txt file: "hcexfgijkamdnoqrzstuvwybpl"
Please write a program to read the data content, sort the data and write it to SS Txt.
import java.io.*; import java.util.Arrays; public class IOTest2 { public static void main(String[] args) throws IOException { //Create character buffered input stream object BufferedReader br = new BufferedReader(new FileReader("s.txt")); String s = br.readLine(); br.close(); //Convert string to character array char[] chars = s.toCharArray(); //sort method sorting in Arrays tool class Arrays.sort(chars); //Create character buffered output stream object BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt")); bw.write(chars); bw.flush(); bw.close(); } }
import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; public class DataOutputStreamDemo1 { public static void main(String[] args) throws Exception { //Create byte output stream operation basic data type data DataOutputStream bos = new DataOutputStream(new FileOutputStream("b1.txt")); //Write basic types of data bos.writeByte(1); bos.writeShort(5); bos.writeInt(10); bos.writeLong(100); bos.writeFloat(13.45F); bos.writeDouble(12.34); bos.writeChar('d'); bos.writeBoolean(true); //Release resources bos.close(); } }
import java.io.*; public class DataInputStreamDemo1 { public static void main(String[] args) throws Exception { write(); read(); } public static void read() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream("b1.txt")); byte b=dis.readByte(); System.out.println(b); short s= dis.readShort(); System.out.println(s); int i= dis.readInt(); System.out.println(i); long l= dis.readLong(); System.out.println(l); float f= dis.readFloat(); System.out.println(f); double d= dis.readDouble(); System.out.println(d); char c= dis.readChar(); System.out.println(c); boolean o= dis.readBoolean(); System.out.println(o); dis.close(); } private static void write() throws IOException { DataOutputStream dos = new DataOutputStream(new FileOutputStream( "dos.txt")); dos.writeByte(1); dos.writeShort(20); dos.writeInt(300); dos.writeLong(4000); dos.writeFloat(12.34f); dos.writeDouble(12.56); dos.writeChar('a'); dos.writeBoolean(true); dos.close(); } }
Serialization: store objects in a text file or database in the same way as a stream or transfer them over the network
Object -- stream data: ObjectOutputStream
Deserialization: restore the stream object data in the text file or the stream data in the network to an object
Stream data -- object: ObjectInputStream
Test class
import java.io.*; public class ObjectStreamDemo1 { public static void main(String[] args) throws Exception { //Write method to store the object into a file is actually to persist the object write(); //Read method: restore the stream object data in the text file or the stream data in the network to an object read(); } public static void read() throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt")); Object o = ois.readObject(); ois.close(); } public static void write() throws Exception { ObjectOutput oo = new ObjectOutputStream(new FileOutputStream("obj.txt")); //Create an object Person person = new Person("Xiao Ming", 18); oo.writeObject(person); oo.close(); } }
Person class
Deserialized exception:
NotSerializableException
Class serialization is implemented by Java io. The class of the serializable interface is enabled.
Classes that do not implement this interface will not serialize or deserialize any state.
All subtypes of a serializable class are serializable.
The serialization interface has no methods or fields and is only used to identify serializable semantics.
InvalidClassException: com.shujia.wyh.day24.Person;
local class incompatible:
stream classdesc serialVersionUID = -6572568087538942853,
local class serialVersionUID = 2880662336900677170
Why is there such a problem?
The Person class implements the Serializable interface, which is a tag interface. The tag here is actually a tag value
Suppose at the beginning, the value of this tag is id = 100
Before modifying Person:
Person.class -- id:100
When writing data: obj txt -- id:100
When reading data: obj txt -- id:100
After modification: (delete private)
Person.class -- id:200
When writing data: obj txt -- id:100
When reading data: obj txt -- id:100
In the actual development, we sometimes have such problems. What should we do? When we do it normally, write the data again and read it again
However, in real business, it is definitely not allowed to insert the same data multiple times.
What should we do?
In this question, we need to think about the essence. The essence is that if the two serial numbers are the same, if there is a way to change the class, it will not affect the id value
Just fine.
java provides an ID value as we think, which allows us to set the serialVersionUID.
Requirements:
Now I don't want to store the age in the file when serializing
java provides a keyword that allows us to choose which members are not serialized in the serialization process
It's called transient
import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 7649840165648125569L; private String name; int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
user: root
password: 123456
import java.util.Properties; public class PropertiesDemo { public static void main(String[] args) { Properties properties = new Properties(); properties.setProperty("user","root"); properties.setProperty("password","123456"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); System.out.println(user+"--"+password); } } result: root--123456
Background thread: (daemon thread)
public final void setDaemon(boolean on)
There are two kinds of threads in Java: user thread and daemon thread
User thread: before learning multithreading, the running threads are user threads
Daemon thread: the so-called daemon thread refers to a general service thread provided in the background when the program is running. For example, the garbage collection thread is a daemon thread
And this thread does not necessarily exist, so conversely, as long as the program has a daemon thread, the program will not terminate.
How to set the daemon thread?
public final void setDaemon(boolean on)
be careful:
1. The daemon thread must be set before starting
2. When the running program has only one thread and this thread is a guard thread, the Java virtual machine exits (the program stops)
//MyDaemonThread public class MyDaemonThread extends Thread{ @Override public void run() { for (int i=1;i<=200;i++){ System.out.println(getName()+":"+i); } } }
//ThreadDaemonDemo public class ThreadDaemonDemo { public static void main(String[] args) { MyDaemonThread t1 = new MyDaemonThread(); MyDaemonThread t2 = new MyDaemonThread(); MyDaemonThread t3 = new MyDaemonThread(); t1.setName("Liu Bei"); t2.setName("Guan Yu"); t2.setDaemon(true); t3.setName("Fei Zhang"); t3.setDaemon(true); t1.start(); t2.start(); t3.start(); } }