Moment For Technology

Java Basics (8) - character streams, code tables, threads

Posted on June 24, 2022, 1:59 a.m. by Christian Campbell
Category: The back-end Tag: notes

directory

Characters of the flow

Why do character streams occur

Code table

Summary: use what kind of rules encoding, it is necessary to use the corresponding rules decoding, otherwise there will be garbled code

Character stream encoding and decoding

Character buffered stream features

IO summary

thread

Multithreaded implementation

Class Thread

Method 1: Inherit Thread

Two quick questions:

Thread scheduling

The thread of control

Thread synchronization

Case study: Selling tickets

Ticketing case data security problem solving


 

Characters of the flow

Storage of one Chinese character: 2 bytes for GBK encoding and 3 bytes for UTF-8 encoding

 

Why do character streams occur

Since byte stream operation Chinese is not particularly convenient, AVA provides character stream character stream = byte stream + encoding table when copying text file with byte stream, the text file will also have Chinese, but there is no problem, the reason is that eventually the bottom operation will automatically combine bytes into Chinese, how to identify Chinese?

  • When Chinese characters are stored, the first byte is always negative no matter which encoding is chosen

 

Code table

Basic knowledge:

  • The information stored in a computer is expressed in binary numbers. The characters we see on the screen, such as English and Chinese characters, are the result of binary number conversion
  • Storing characters in a computer according to certain rules is called encoding. Conversely, the binary number stored in the computer in accordance with a certain rule of parsing display, known as decoding. Here's an emphasis: Stored in A code, it must be parsed in A code in order to display the correct text symbol. Otherwise, it will cause garbled characters

Character encoding: A set of rules for correspondence between natural language characters and binary numbers (A.65)

Summary: use what kind of rules encoding, it is necessary to use the corresponding rules decoding, otherwise there will be garbled code

Character stream encoding and decoding

Character stream abstract base class

  • Reader: Abstract class for a character input stream
  • Writer: Abstract class for the character output stream

Two classes for character streams related to encoding and decoding problems:

  • InputStreamReader
  • OutputStreamWriter

InputStreamReader: bridge from byte stream to character stream

  • It reads bytes and decodes them into characters using the specified encoding
  • The character set it uses can be specified by name, can be explicitly specified, or can accept the platform's default character set

OutputStreamWriter: a bridge from a character stream to a byte stream

  • A bridge from a character stream to a byte stream, encoding written characters as bytes using the specified encoding
  • The character set it uses can be specified by name, can be explicitly specified, or can accept the platform's default character set

Code:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class ZiFu {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("D: \ \ \ \ eclipse \ \ API File. TXT");
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write("Go China!"); osw.close(); }}Copy the code

Character buffered stream features

BufferedWriter:

  • Void newLine(): writes - - line delimiter. The line delimiter string is defined by system properties

BufferedReader:

  • Public String readLine(): read-line text. The result is a string containing the contents of the row, excluding any line terminating characters, or null if the end of the stream has been reached

Code:

public class ZiFu {
    public static void main(String[] args) throws IOException {
// // Creates a character buffered output stream
// BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\eclipse\\API document \\ file.txt "));
// // Write data
// for (int i = 0; i  10; i++) {
// bw.write("hello" + i);
// bw.write("\r\n");
// bw.newLine();
// bw.flush();
/ /}
// // Releasing resources
// bw.close();
        // Create a character buffered input stream
        BufferedReader br = new BufferedReader(new FileReader("D: \ \ \ \ eclipse \ \ API File. TXT"));
        String by;
        while((by=br.readLine())! =null){ System.out.print(by); } br.close(); }}Copy the code

Results:

IO summary

 

thread

Thread: is a single sequential control flow in a process, a path of execution

  • Single-threaded: A process that has only one path of execution is called a single-threaded program
  • Multithreading: IF a process has more than one execution path, it is called multithreaded program

Multithreaded implementation

Class Thread

  • public class Thread
    extends Object
    implements Runnable
    Copy the code

    Threads are threads of execution in a program. The Java virtual machine allows applications to execute multiple threads of execution simultaneously.

    Each thread has priority. A thread with a higher priority executes before a thread with a lower priority. Each thread may or may not be marked as a daemon. When code running in a Thread creates a new Thread object, the priority of the new Thread is initially set to equal the priority of the Thread that created it, and is a daemon Thread if and only if the Thread that created it is a daemon.

    When a Java virtual machine starts, there is usually a non-daemon thread (usually calling a method named main of some specified class). The Java virtual machine continues to execute threads until one of the following occurs:

    There are two ways to create a new thread of execution. One is to declare a class as a subclass of Thread. This subclass should override the run method Thread. You can then assign and start instances of subclasses.

    • The Exit method of the Runtime class has been called, and the security manager has allowed the exit operation.

    • All threads that are not daemon threads are dead, either from a call back to the run method or from a run thrown outside the run method.

  • Another way to create a thread is to declare the implementation class Runnable interface. That class then implements the run method. An instance of the class can then be assigned, passed as a parameter when Thread is created, and started.

Method 1: Inherit Thread

  • Define a class MyThread that inherits Thread
  • Override the run() method in MyThread
  • Create an object of the MyThread class
  • Starting a thread

Two quick questions:

  • Why override the run() method?

    • Because run() is used to encapsulate code that is being executed by threads
  • What is the difference between the run() and start() methods?

    • Run (): Encapsulates code executed by a thread, called directly, equivalent to a normal method call
    • Start (): starts the thread; The JVM then calls the thread's run() method

Test code:

public class MyThread {
    public static void main(String[] args) {
        // Two threads
        ThreadDemo my1 = new ThreadDemo();
        ThreadDemo my2 = new ThreadDemo();
        // There is no multi-thread execution, but a single thread execution
// my1.run();
// my2.run();
        //start() causes this thread to start executing; The Java virtual machine calls the run method of this thread.my1.start(); my2.start(); }}Copy the code
MyThread overwrites the run() method in MyThread to create an object of MyThread */
public class ThreadDemo extends Thread {
    @Override
    public void run(a) {
        for (int i = 0; i  100; i++) {
            System.out.println(getName()+ ":"+ i); }}}Copy the code

Results:

Methods of setting and getting the name of a Thread in the Thread class

  • Void setName(String name): Changes the name of this thread to equal the parameter name
  • String getName(): Returns the name of this thread

Thread scheduling

There are two scheduling models for threads

  • Time-sharing scheduling model: All threads take turns to use the CPU and allocate the CPU time slice equally for each thread
  • Preemptive scheduling model: priority is given to threads with higher priority to use THE CPU. If threads of the same priority are selected randomly, threads with higher priority get more CPU slices

Java uses a preemptive scheduling model. If the computer has only one CPU, then the CPU can only execute one instruction at a time, and the thread only gets a slice of CPU time, or usage, to execute the instruction. So the execution of multithreaded programs is random, because who grabs the CPU is not necessarily right

Public final int getPriority(): returns the priority of this thread system.out.println (tp1.getPriority ()); Public final void setPriority(int newPriority): changes the priority of this thread tp1.setpriority (10000);

The highest priority is 10, the lowest priority is 1, and the default is 5

 

The thread of control

Code: the thread pauses for 1S

public class ThreadDemo extends Thread {
    @Override
    public void run(a) {
        for (int i = 0; i  100; i++) {
            System.out.println(getName()+ ":" + i);
            try {
                Thread.sleep(1000);
            } catch(InterruptedException e) { e.printStackTrace(); }}}}Copy the code
public class MyThread {
    public static void main(String[] args) {
        // Two threads
        ThreadDemo my1 = new ThreadDemo();
        ThreadDemo my2 = new ThreadDemo();
        ThreadDemo my3 = new ThreadDemo();

        my1.setName("Cao cao");
        my2.setName("Liu table");
        my3.setName("Sun ce"); my1.start(); my2.start(); my3.start(); }}Copy the code

Results:

 

Thread synchronization

Case study: Selling tickets

Demand: a cinema is currently showing domestic blockbusters, a total of 100 tickets, and it has 3 Windows to sell tickets, please design a program to simulate the cinema to sell tickets

Private int tickets= 100; private int tickets= 100; private int tickets= 100; ② In the SellTicket class write run0 method to sell tickets, code steps are as follows

  • A: If the number of votes is greater than zero, sell the tickets and tell me which window they are from
  • B: After the tickets are sold, the total number of votes will be reduced by one
  • C: There are no tickets, and people may ask, so there is an endless loop to keep the action of selling tickets going on

③ Define a test class SellTicketDemo, which contains the main method

  • A: Create an object of the SellTicket class
  • B: Create three Thread class objects, take the SelITicket object as the constructor parameter, and give the corresponding window name
  • C: Starts the thread
packageCn. Itcast. Day8. Buy a ticket;public class SellTicket implements Runnable {
    private int tickets = 100;

    @Override
    public void run(a) {
// A: If the number of tickets is greater than 0, sell the tickets
// B: After the tickets are sold, the total number of votes will be reduced by 1
// C: There are no tickets left, so there is an endless loop to keep the operation going
        // Problem: the same ticket appears multiple times - cause: thread execution is random
        boolean flag = true;
        while (flag == true) {if (tickets  0) {try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // T1 takes control of the CPU's execution, and in console output, window 1 sells 1 ticket
                // Assuming t1 continues to have CPU actuators, tickets--; operation
                System.out.println(Thread.currentThread().getName()+"For sale"+tickets+"Ticket");
                tickets--;
            }
            else {
                System.out.println("The tickets are sold out.");
                flag = false; }}}}Copy the code
packageCn. Itcast. Day8. Buy a ticket;public class SellTicketDemo {
    public static void main(String[] args) {
// A: Creates an object of the SellTicket class
// B: Create three Thread class objects, take the SelITicket object as the constructor argument, and give the corresponding window name
// C: starts the thread
        SellTicket st = new SellTicket();

        Thread t1 = new Thread(st,"Window 1");
        Thread t2 = new Thread(st,"Window 2");
        Thread t3 = new Thread(st,"Window 3"); t1.start(); t2.start(); t3.start(); }}Copy the code

Ticketing case data security problem solving

Why did it go wrong? (This is also how we determine whether multithreaded programs have data security issues

  • Whether it's a multi-threaded environment
  • Whether there is shared data
  • Whether multiple statements operate on shared data

How to solve the multithreaded security problem?

  • Basic idea: let the program have no security problem environment

How do you do that?

  • Lock up code that operates on shared data so that only one thread can execute it at any time
  • Java provides blocks of synchronized code to do this

 

 

 

 

 

Learn together and make progress together. If there are any mistakes, please comment

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.