当前位置:网站首页>Research on Android multithreading (4) -- from an interview question
Research on Android multithreading (4) -- from an interview question
2022-07-29 10:22:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack , I wish every programmer can learn more languages .
There is one such Interview questions : Turn on a child thread to run at the same time as the main thread , Child thread output 10 Next, the main thread outputs 100 Time , repeat 50 Time . First look at the following code :
package com.maso.test;
/**
*
* @author Administrator
* Two threads , There is a main thread , The first thread runs the output first 10 Time , The main thread then runs the output 100 Time , repeat 50 Time
*/
public class ThreadTest3 implements Runnable{
private static Test test;
@Override
public void run() {
for(int i=0; i<50; i++){
test.f1(i);
}
}
public static void main(String[] args) {
test = new Test();
new Thread(new ThreadTest3()).start();
for(int i=0; i<50; i++){
test.f2(i);
}
}
/**
* Classify control and logic and data ( This class is data )
* @author Administrator
*
*/
static class Test{
private boolean isf1 = true;
/**
* Output 10 Time
*/
public synchronized void f1(int j){
if(!isf1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=1; i<=10; i++){
System.out.println(Thread.currentThread().getName() + " The first " + j + " Second round patrol , Output " + i);
}
isf1 = false;
notify();
}
/**
* Output 100 Time
*/
public synchronized void f2(int j){
if(isf1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=1; i<=100; i++){
System.out.println(Thread.currentThread().getName() + " The first " + j + " Second round patrol , Output " + i);
}
isf1 = true;
notify();
}
}
}
The above inference uses if sentence , There seems to be no problem doing so , In fact, it is not safe to do so , Because the thread may be falsely awakened while waiting , So we need to use while sentence . In addition, we are using wait and notify There are several points to pay attention to when :
1、 call object Of wait Methods and notity When the method is used , You have to get object The object of the lock ( Must be written in synchronized in ).
2、 Suppose you call object Of wait Method , Then the thread releases the object lock .
3、 hypothesis A1、A2、A3 All in object.wait(), be B call object.notify() Can only wake up A1、A2、A3 One of them ( Which one is detailed by JVM decision )
4、object.notifyAll() Can wake up all .
5、B Wake up A When ,B Suppose you still hold the object lock , Wait until B After releasing the lock ,A To have a chance to run .
Sleep and Wait What's the difference ?
sleep() Does not release the object lock ,wait() Release object lock . But wait() and sleep() Can pass through interrupt() Method to break the thread's pause state , This causes the thread to immediately throw InterruptedException. Assuming that thread A Want to end the thread immediately B, Can be applied to threads B Corresponding Thread The instance interrupt Method . Suppose that at this moment, the thread B is wait/sleep/join, The thread B Will throw it right away InterruptedException, stay catch() {} In the direct return The thread can end safely . It should be noted that ,InterruptedException It's the thread itself that throws it from the inside , Is not interrupt() Method . Call... On a thread interrupt() when , Suppose the thread is running normal code , Then the thread will not throw InterruptedException. But , Once the thread enters wait()/sleep()/join() after , Will immediately throw out InterruptedException.
Let's take a look at the life cycle of threads :
The method to realize thread scheduling is as follows :
1、sleep(): This thread is to let the thread sleep for a certain time , Need to capture InterruptedException
2、yield(): Pause current thread , Let threads with the same priority run , Assuming that there is no thread with the same priority, it will not work . When it works, it will give way CPU The elapsed time , Get ready .
3、join(): Let a thread wait for the call join Method, and then continue to run .
Look at a piece of code :
public class ThreadTest4 implements Runnable{
private static int a = 0;
@Override
public void run() {
for(int i=0; i<10; i++){
a++;
}
}
public static void main(String[] args) {
new Thread(new ThreadTest4()).start();
System.out.println(a);
}
}
This code will output 10 Do you ? The answer is no , Because after starting the child thread , Immediately output a Value , At this time, the sub thread pair a No operation yet . Changes such as the following :
public class ThreadTest4 implements Runnable{
private static int a = 0;
@Override
public void run() {
for(int i=0; i<10; i++){
a++;
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ThreadTest4());
t.start();
t.join();
System.out.println(a);
}
}
This time output 10,join() The role of methods can be seen , It will make other threads wait for the thread to finish running before running .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/118988.html Link to the original text :https://javaforall.cn
边栏推荐
- Talk about multithreaded concurrent programming from a different perspective without heap concept
- 皕杰报表之文本附件属件
- Mongodb aggregation statistics
- [paper reading] i-bert: integer only Bert quantification
- Science fiction style, standard 6 airbags, popular · yachts from 119900
- The maximum length of VARCHAR2 type in Oracle is_ Oracle modify field length SQL
- [jetson][转载]jetson上安装pycharm
- [untitled]
- Soft exam summary
- Google Earth engine (GEE) -- calculate the location of the center point, the external boundary, the external polygon, fuse and simplify the boundary and return it to the vector set
猜你喜欢
Some suggestions for programmers to leave single
Geeer's happiness | is for the white whoring image! Analysis and mining, NDVI, unsupervised classification, etc
[FPGA tutorial case 19] factorial operation through multiplier
Knowledge points of common interview questions: distributed lock
This is the right way for developers to open artifacts
根据给定字符数和字符,打印输出“沙漏”和剩余数
Follow teacher Tian to learn practical English Grammar (continuous update)
【黑马早报】每日优鲜回应解散,多地已无法下单;李斌称蔚来将每年出一部手机;李嘉诚欲抄底恒大香港总部大楼;今年国庆休7天上7天...
[HFCTF 2021 Final]easyflask
After eating Alibaba's core notes of highly concurrent programming, the backhand rose 5K
随机推荐
[log frame]
[wechat applet] interface generates customized homepage QR code
静态资源映射
PDF处理还收费?不可能
This is an incomplete data competition Yearbook!
Skiasharp's WPF self drawn bouncing ball (case version)
Follow teacher Tian to learn practical English Grammar (continuous update)
Leetcode question brushing - sorting
[dark horse morning post] Youxian responded to the dissolution every day, and many places have been unable to place orders; Li Bin said that Wei Lai will produce a mobile phone every year; Li Ka Shing
通俗易懂讲解梯度下降法!
How big is the bandwidth of the Tiktok server for hundreds of millions of people to brush at the same time?
Encyclopedia of introduction to machine learning - 2018 "machine learning beginners" official account article summary
不堆概念、换个角度聊多线程并发编程
Is there any charge for PDF processing? impossible
Docker installation, redis configuration and remote connection
高效能7个习惯学习笔记
PAHO cross compilation
Follow teacher Li to learn online generation - matrix (continuously updated)
Two MySQL tables with different codes (utf8, utf8mb4) are joined, resulting in index failure
Summary of window system operation skills