1. Java basic programming structure

1.1 Data Types

Java is a strongly typed language and you must declare a type for every variable.

There are eight basic types in Java:

Type Storage Requirement Value range int 4 bytes -2 147 483 648 to 2 147 483 647 Short 2 bytes -32 768 to 32 767 Long 8 bytes -9 233 372 036 854 775 808 to 9 233 372 036 854 775 807 byte 1 -128 ~ 127 Float 4 bytes about ±3.402 823 47E+38F double 8 bytes about ±1.797 693 134 862 315 70E+308 char booleanCopy the code

1.2 the operator

  • && logic and operators: 0 out of 0, all 1 out of 1

Evaluate in “short circuit” mode

expression1 && expression2

When the value of the first expression is false, the result cannot be true. The second expression can be used to satisfy the second expression if the first expression is true

  • | | logic or the operator: there is 1 out of 1, all 0 0

expression1 && expression2

If the value of the first expression is true, the result is true and the second expression does not need to be evaluated

  • Ternary operator? :

condition ? expression1 && expression2

When condition is true, it is the value of the first expression, and when false, it evaluates the value of the second expression

1.2.1 bit operators

When working with integer types, you can operate directly on the bits that make up the value of an integer.

  • Operators include: & and | or not ~ ^

Applied in Boolean value & | operator will also get a Boolean value, but not with the method of short circuit

  • Displacement operation:
The following uses 8 bits of byte as an example: Positive number: 20 << 2 Complement: (The complement of a positive number is the same as the inverse of the source code) 0001 0100 0101 0000 result = 80 Negative number: -20 << 2 complement: (the inverse of a negative number: 1110 1100 left: 1011 0000 Original: 1101 0000 result = -80 >> right if sign bit is 0, complement 0 is 1, complement 1 positive: 20 >> 2 Complement: 0000 0101 result = 5 negative: -20 >> 2 Complement: 1110 1100 right: 1111 1011 1000 0101 result = -5 >>> right move No sign right move (logical right move) Whether the sign bit is 0 or 1, the right move is the high-order complement 0 20 >>> 2 result = 5-20 >>> 1 result = 5Copy the code

1.3 the code block

  • Static code block:

It runs when the class is loaded and only once. When code needs to be executed at project startup, you can use static code blocks such as many configuration files that need to be loaded for a project startup

  • Construct code block:

The constructor code block is called when an object is created, it’s called every time the object is created, it’s just like the constructor, it initializes the object, and it’s executed every time an object is created. Constructors, on the other hand, are not always executed for each object. (Multiple constructors are used to initialize objects with different parameters.)

  • Construction method:

The method name must be the same as the class name and no return value is used to define the initialized state when creating the object

  • Common code block:

A code block defined in a method

Order of execution:

Public class Demo01 {static {system.out.println (" execute static code block "); } public demo01() {system.out.println (" execute constructor "); } {system.out.println (" Execute construct code block "); } public void SSS (){{system.out.println (" execute ordinary code block "); } } public static void main(String[] args) { new demo01().sss(); }}Copy the code

1.4 String (String)

7. The concurrent

1. What is concurrency?

In a learning operating system, concurrency refers to a period of time when several programs are running between start and finish, and these programs are all running on the same processor, but only one program is running on the processor at any point in time.

For example, eating while playing on your phone, your brain is doing only one thing at a time, but switching at high speed is so short that it feels like it’s happening simultaneously

  • Program: an ordered collection of instructions, which itself has no meaning of operation, it is a static entity
  • Process: a running activity of a program in a computer on a data set. It is the basic unit of resource allocation and scheduling in the system

A process is a dynamic entity that has its own life cycle. It is created, run for scheduling, wait for resources or events, and undo for task completion. It reflects the whole dynamic process of a program running on a certain data set.

  • Thread: The smallest unit in which an operating system can schedule operations. It is contained within the process and is the actual operating unit within the process. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel.

2. Three ways Java can create threads

2.1 Inheriting Thread classes (not recommended: Avoid OOP single inheritance limitations)

public class Test01 extends Thread{ @Override public void run() { //do some work } public static void main(String[] args) { new Test01().start(); }}Copy the code

2.2 Implementing the Runnable Interface

public class Test01 { @Override public void run() { //do some work } public static void main(String[] args) { Runnable t1 = new Test01(); new Thread(t1).start(); }}Copy the code

2.3 Implement the Callable interface

@Override public Boolean call() throws Exception { //do some work return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { Test03 t1 = new Test03(); Test03 t2 = new Test03(); Test03 t3 = new Test03(); / / create the execution services ExecutorService ser = Executors. NewFixedThreadPool (3); Future<Boolean> result1 = ser.submit(t1); Future<Boolean> result2 = ser.submit(t2); Future<Boolean> result3 = ser.submit(t3); Boolean r1 = result1.get(); boolean r2 = result1.get(); boolean r3 = result1.get(); Ser.shutdownnow (); }}Copy the code

3. Concurrent problems in the simulation program of tortoise and rabbit race

Private static String implements Runnable{// private static String implements Runnable; @Override public void run() { for (int i = 0; i <= 100; I++){thread.currentthread ().getname ().equals(" rabbit ")){try {thread.sleep (1); } catch (InterruptedException e) { e.printStackTrace(); If (iswiner(I)){break; } system.out.println (thread.currentThread ().getName()); }} public Boolean iswiner(int steps){if(winner! = null){// Victor already exists return true; }else { if (steps == 100){ winner = Thread.currentThread().getName(); System.out.println("winner is "+winner); return true; } } return false; } public static void main(String[] args) {new Thread(new Race()," turtle ").start(); New Thread(new Race()," rabbit ").start(); }}Copy the code

4. Thread status

4.1 Stopping a Thread

//1. It is recommended that the thread stop normally -- "the number of times used, do not recommend an infinite loop //2. Public class Test04 implements Runnable{//1. Private Boolean flag = true; @override public void run() {while (flag){//do some work}} Public void stop(){this.flag = false; } public static void main(String[] args) { Test04 t1 = new Test04(); new Thread(t1).start(); for (int i = 0; i < 100; I ++) {if (I == 90){// Call stop to switch flags, stop thread t1.stop(); }}}}Copy the code

4.2 Thread Spin-down (Blocked)

4.3 Thread comity

4.4 the Join

public class TestJoin implements Runnable{

@override public void run() {//do some work system.out.println (" queue "); } public static void main(String[] args) throws InterruptedException { TestJoin testJoin = new TestJoin(); Thread thread = new Thread(testJoin); thread.start(); for (int i = 0; i < 100; i++) { if (i == 20){ thread.join(); }}}}Copy the code

5 Thread status observation

Public class TestState {public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(() -> { for (int i = 0; i < 2; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("////////"); }); Thread.state State = t1.getState(); System.out.println(state); T1.start (); state = t1.getState(); System.out.println(state); while (state ! Thread.sleep(500); // the Thread is TERMINATED. state = t1.getState(); System.out.println(state); }}}Copy the code

5.1 Priority of threads

public class TestPriority { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); Mypriority mypriority = new Mypriority(); Thread t1 = new Thread(mypriority); Thread t2 = new Thread(mypriority); Thread t3 = new Thread(mypriority); Thread t4 = new Thread(mypriority); // setPriority t1.setpriority (1); t1.start(); t2.setPriority(5); t2.start(); t3.setPriority(Thread.MAX_PRIORITY); t3.start(); t4.setPriority(8); t4.start(); } } class Mypriority implements Runnable{ @Override public void run() { //do some work System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); }}Copy the code

5.2 Daemon Thread

Public class TestDaemon {public static void main(String[] args) {God God = new God(); People people = new People(); Thread thread = new Thread(god); thread.setDaemon(true); Thread.start (); new Thread(people).start(); }} class God implements Runnable{@override public void run() {while (true){system.out.println (" implements Runnable "); } } } class People implements Runnable{ @Override public void run() { for (int i = 0; i < 10; I++) {system.out.println (" every day is happy to live "); } System.out.println("======= GoodBye World! = = = = = = = = "); }}Copy the code

6. Synchronize threads

When dealing with multiple threads, multiple threads access the same object, and some also want to modify this thread object, by this time we need to thread synchronization, thread synchronization is actually a kind of wait for mechanism, multiple threads need to access the object into the waiting pool of objects Form a queue, waiting for the end of a thread used before, and execution of a thread

6.1 Queues and Locks

6.2 Examples of Thread Insecurity

  • Buying tickets is not safe
Public class UnsafeBuyTicket {public static void main(String[] args) {BuyTicket BuyTicket = new BuyTicket(); New Thread(buyTicket," buyTicket ").start(); New Thread(buyTicket," buyTicket ").start(); New Thread(buyTicket," buyTicket ").start(); }} class ticket implements Runnable{// int ticketNum = 10; boolean falg = true; @override public void run() {// buy while (falg){buy(); }} private void buy(){if (ticketNum <= 0){falg = false; return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } system.out.println (thread.currentThread ().getName()+" get "+ticketNum--); }}Copy the code

  • Banks make unsafe withdrawals
// Two people go to the bank to withdraw money, Public class UnsafeBank {public static void main(String[] args) {// Account Account = new Account(100, "tourist fund "); Drawing zc = new Drawing(Account, 50, "sub "); Drawing ww = new Drawing(Account, 100, "slightly "); zc.start(); ww.start(); } // Account class Account{int money; // Balance String name; Public Account(int money,String name){this.money = money; this.name = name; }} class extends Thread{Account Account; // account // how much money int darwingMoney; // Now how much money int nowMoney; public Drawing(Account account,int darwingMoney,String name){ super(name); this.account = account; this.darwingMoney = darwingMoney; } // Override public void run() {if (account.money - darwingMoney < 0){ System.out.println(thread.currentThread ().getName()+" insufficient balance "); return; } // balance = balance - money taken out account.money = account.money - darwingMoney; // nowMoney = nowMoney + darwingMoney; System.out.println(account.name+", your account balance is "+account.money); System.out.println(this.getName()+" nowMoney "); }}Copy the code

  • Thread-unsafe collection
Public class UnsafeList {public static void main(String[] args){List List = new ArrayList(); for (int i = 0; i < 1000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); }}Copy the code

Two threads operating on the same part of the array at the same time caused the data to be overwritten

6.3 Synchronization Method and Synchronize Block synchronize

The solution to example 1 is to add synchronize to the method

private synchronized void buy(){
Copy the code

Solution in Example 2: Synchronize a synchronization block locks the Account object

Synchronized (account){if (account. Money - darwingMoney < 0){synchronized (account){ System.out.println(thread.currentThread ().getName()+" insufficient balance "); return; } // balance = balance - money taken out account.money = account.money - darwingMoney; // nowMoney = nowMoney + darwingMoney; System.out.println(account.name+", your account balance is "+account.money); System.out.println(this.getName()+" nowMoney "); }Copy the code

The solution to example 3

 new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
Copy the code

7. A deadlock

// Two threads own each other the resources that the object needs, Public class Deadlock {public static void main(String[] args) {Makeup Makeup = new Makeup(0, "white white "); Makeup makeup1 = new Makeup(1, "sleeping beauty "); makeup.start(); makeup1.start(); }} class Lipstick{} class Makeup extends Thread {static Lipstick = new Lipstick();  static Mirror mirror = new Mirror(); int choice; // Select String girlName; Public Makeup(int choice, String girlName) {this.choice = choice; this.girlName = girlName; } @override public void run() {makeup {makeup(); } catch (InterruptedException e) { e.printStackTrace(); }} private void makeup() throws InterruptedException {if (choice == 0) {synchronized (lipstick) System.out.println(this.girlname + "get lipstick lock "); Thread.sleep(1000); Synchronized (mirror) {system.out.println (this.girlname + "obtain mirror lock "); }}} else {synchronized (mirror) {system.out.println (this.girlname + "obtain mirror "); Thread.sleep(1000); Synchronized (lipstick) {// synchronized (lipstick) {system.out.println (this.girlname + "get lipstick "); } } } } }Copy the code

The program has been deadlocked and stopped here

7.1 the Lock

Class BuyTicket implements Runnable{// int ticketNum = 10; private static ReentrantLock lock = new ReentrantLock(); boolean falg = true; @override public void run() {falg {try{lock.lock(); buy(); }finally {// unlock lock.unlock(); }}}Copy the code

7.2 Synchronize compared with Lock

8. Thread collaboration