Java–Multithreading–Three cases of thread state, thread priority, daemon thread, thread insecurity and synchronized keyword
Thread status
package com.zy.thread;
/**
*description: Java--Multithreading--Thread Status Observation
*@program: basic syntax
*@author: zy
*@create: 2023-03-22 20:55
*/
public class StudyThreadState {<!-- -->
public static void main(String[] args) throws InterruptedException {<!-- -->
Thread thread = new Thread(()->{<!-- -->
for (int i = 0; i < 5; i ++ ) {<!-- -->
try {<!-- -->
Thread. sleep(1000);
} catch (InterruptedException e) {<!-- -->
e.printStackTrace();
}
}
System.out.println("................................");
});
// watch status
Thread. State state = thread. getState();
// Freshman NEW
System.out.println(state);
// watch starts
thread. start();
// Running status RUNNABLE
state = thread. getState();
System.out.println(state);
while (state != Thread.State.TERMINATED){<!-- -->
Thread. sleep(100);
// update status TIMED_WAITING/TERMINATED
state = thread. getState();
System.out.println(state);
}
/*
A thread after death cannot be started again
*/
//thread.start();
}
}
Thread priority
package com.zy.thread;
/**
*description: Java--Multithreading--Thread Priority
*@program: basic syntax
*@author: zy
*@create: 2023-03-22 21:07
*/
public class StudyThreadPriority {<!-- -->
/*
It is recommended to set the priority before starting;
A low priority just means that the probability of cpu scheduling is low, and it does not guarantee that it will not be called. (performance inversion)
*/
public static void main(String[] args) {<!-- -->
// Main thread default priority
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);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
// set priority
t2.setPriority(Thread.MIN_PRIORITY);
t3. setPriority(4);
t4.setPriority(Thread.MAX_PRIORITY);
t1. start();
t2.start();
t3. start();
t4.start();
/*t5.setPriority(-1);
t5.start();
t6. setPriority(11);
t6.start();*/
}
}
class MyPriority implements Runnable{<!-- -->
@Override
public void run() {<!-- -->
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
}
}
Daemon thread
package com.zy.thread;
/**
*description: Java--Multithreading--Daemon thread
*@program: basic syntax
*@author: zy
*@create: 2023-03-22 21:20
*/
public class StudyThreadDaemon {<!-- -->
/*
Threads are divided into user threads and daemon threads;
The virtual machine must ensure that the execution of the user thread is completed;
The virtual machine does not have to wait for the daemon thread to finish executing;
Example: recording operation logs in the background, monitoring memory, waiting for garbage collection...
*/
public static void main(String[] args) {<!-- -->
God god = new God();
Person person = new Person();
Thread thread = new Thread(god);
// Set daemon thread; default false, marked as user thread
thread. setDaemon(true);
// daemon thread start
thread. start();
// user thread start
new Thread(person).start();
}
}
class God implements Runnable{<!-- -->
@Override
public void run() {<!-- -->
while (true){<!-- -->
System.out.println("God bless you");
}
}
}
class Person implements Runnable{<!-- -->
@Override
public void run() {<!-- -->
for (int i = 0; i < 36500; i ++ ) {<!-- -->
System.out.println("You are living happily all your life");
}
System.out.println("==========Goodbye, world!!!============");
}
}
Thread unsafe case
package com.zy.thread.sync;
/**
*description: Java--Multithreading--Thread unsafe buying ticket case
* Thread unsafe: inconsistent data
*@program: basic syntax
*@author: zy
*@create: 2023-03-22 21:41
*/
public class UnsafeBuyTicket {<!-- -->
public static void main(String[] args) {<!-- -->
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"Xiaomi").start();
new Thread(buyTicket,"Xiao Zhang").start();
new Thread(buyTicket,"Xiao Wang").start();
}
}
class BuyTicket implements Runnable{<!-- -->
private int ticketNumbers = 10;
boolean flag = true;
@Override
public void run() {<!-- -->
while (flag){<!-- -->
try {<!-- -->
buy();
} catch (InterruptedException e) {<!-- -->
e.printStackTrace();
}
}
}
/**
* @Description Synchronization method, which locks this object itself
* @author zy
* []
* void
* @date 2023-3-22 22:43
*/
private synchronized void buy() throws InterruptedException {<!-- -->
if(ticketNumbers <=0){<!-- -->
flag = false;
return;
}
Thread. sleep(100);
System.out.println(Thread.currentThread().getName() + "Get the first " + ticketNumbers-- + "tickets");
}
}
package com.zy.thread.sync;
/**
*description: Java--Multithreading--A case of unsafe withdrawal of money
*@program: basic syntax
*@author: zy
*@create: 2023-03-22 21:51
*/
public class UnsafeBank {<!-- -->
public static void main(String[] args) {<!-- -->
Account account = new Account(1000,"Money for buying a house");
Drawing boy = new Drawing(account,50,"You");
Drawing girl = new Drawing(account,100,"girlfriend");
boy. start();
girl. start();
}
}
class Account{<!-- -->
private int money;
private String name;
public Account(int money, String name) {<!-- -->
this.money = money;
this.name = name;
}
public int getMoney() {<!-- -->
return money;
}
public void setMoney(int money) {<!-- -->
this.money = money;
}
public String getName() {<!-- -->
return name;
}
public void setName(String name) {<!-- -->
this.name = name;
}
}
class Drawing extends Thread{<!-- -->
private Account account;
private int drawingMoney;
private int nowMoney;
public Drawing(Account account,int drawingMoney,String name){<!-- -->
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {<!-- -->
// Synchronization blocks, also known as synchronization monitors, are recommended to lock shared resources and need to access modified resources
synchronized (account){<!-- -->
if(account.getMoney() - drawingMoney < 0){<!-- -->
System.out.println(this.getName() + "Insufficient balance, unable to withdraw");
return;
}
try {<!-- -->
// Amplify the occurrence of the problem
Thread. sleep(1000);
} catch (InterruptedException e) {<!-- -->
e.printStackTrace();
}
account.setMoney(account.getMoney()-drawingMoney);
nowMoney = nowMoney + drawingMoney;
System.out.println(account.getName() + "The balance is:" + account.getMoney());
System.out.println(this.getName() + "The money in hand is: " + nowMoney);
}
}
}
package com.zy.thread.sync;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
*description: Java--Multithreading--Collection case of unsafe threads
*@program: basic syntax
*@author: zy
*@create: 2023-03-22 22:13
*/
public class UnsafeList {<!-- -->
public static void main(String[] args) {<!-- -->
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i ++ ) {<!-- -->
new Thread(()->{<!-- -->
synchronized (list){<!-- -->
list.add(Thread.currentThread().getName());
System.out.println("List size:" + list.size() + "===>" + Thread.currentThread().getName());
}
}).start();
}
}
}