java 等待唤醒机制,Java线程等待唤醒机制
記錄面試過程中被問到的幾個需要手寫代碼的小案例
1.請手寫出線程的等待喚醒機(jī)制
案例中兩個線程:SyncSetThread設(shè)置學(xué)生信息,SyncGetThread用來獲取學(xué)生信息,在Student實(shí)體中提供一個標(biāo)記屬性flag,記錄當(dāng)前是否有數(shù)據(jù)。
等待喚醒機(jī)制
設(shè)置信息線程SyncSetThread
/*
* 使用Object的wait() 和 notify() 來實(shí)現(xiàn)等待喚醒機(jī)制
* Created by JackYang on 2017/10/17.
*/
class SyncSetThread implements Runnable {
private final Student student;
SyncSetThread(Student student) {
this.student = student;
}
@Override
public void run() {
int num = 0;
while (true) {
synchronized (student) {
if (student.flag) {
try {
student.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (num % 2 == 0) {
student.name = "JackYang";
student.age = 26;
} else {
student.name = "江一燕";
student.age = 28;
}
++num;
student.flag = true;
student.notify();
//此時喚醒,SyncSetThread和SyncGetThread兩個線程都有同等的機(jī)會去搶占資源
}
}
}
}
獲取信息線程SyncGetThread
class SyncGetThread implements Runnable {
private final Student student;
SyncGetThread(Student student) {
this.student = student;
}
@Override
public void run() {
while (true) {
synchronized (student) {
if (!student.flag) {
try {
//對象中沒有數(shù)據(jù)的時候就等待
student.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(student.name + "---" + student.age);
//數(shù)據(jù)消費(fèi)完了(取出后)改變標(biāo)記
student.flag = false;
student.notify();
//此時喚醒,SyncSetThread和SyncGetThread兩個線程都有同等的機(jī)會去搶占資源
}
}
}
}
測試入口
/*
* 線程的等待喚醒機(jī)制,實(shí)現(xiàn)一人一次有規(guī)律
* Created by JackYang on 2017/10/17.
*/
public class TestSyncThread {
public static void main(String[] args) {
Student student = new Student();
SyncSetThread syncSetThread = new SyncSetThread(student);
SyncGetThread syncGetThread = new SyncGetThread(student);
Thread thread1 = new Thread(syncSetThread);
Thread thread2 = new Thread(syncGetThread);
thread1.start();
thread2.start();
}
}
2.請手寫出線程死鎖代碼
這個沒得商量,直接上代碼
/**
* 死鎖代碼
* Created by JackYang on 2017/10/17.
*/
class DieThread extends Thread {
private boolean flag;
DieThread(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
//防止一次卡不住
while (true) {
synchronized (MyLock.lockA) {
System.out.println("true lockA");
synchronized (MyLock.lockB) {
System.out.println("true lockB");
}
}
}
} else {
while (true) {
synchronized (MyLock.lockB) {
System.out.println("false lockB");
synchronized (MyLock.lockA) {
System.out.println("false lockA");
}
}
}
}
}
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的java 等待唤醒机制,Java线程等待唤醒机制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020idea插件怎么同步_VScod
- 下一篇: java引用传递_理解Java中的引用传