线程的交互
2019-07-04 本文已影响0人
不知所言bzsy
题目为:要求:子线程运行执行 10 次后,主线程再运行 5 次。这样交替执行三遍
大致思路为,创建一个子线程和main函数本身的主线程。两个线程来操控程序,然后使用wait 和 notify来实现交替效果
public class 线程的交互 {
private boolean mainflag = true;
public static void main(String[] args) {
线程的交互 bus = new 线程的交互();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3 ; i++ ){
bus.sonMethod();
}
}
}).start();
for (int i = 0 ; i < 3 ;i ++){
bus.mainMethod();
}
}
private synchronized void sonMethod() {
if (!mainflag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10 ; i++ ){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+i);
}
mainflag = false;
notify();
}
private synchronized void mainMethod() {
if (mainflag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5 ; i++ ){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+i);
}
mainflag = true;
notify();
}
}
值得注意的是,wait notity notifyAll必须配合synchronized使用,因为这写方法调用的时候都需要释放锁,如果没有锁汇报异常。所以需要synchronized来获取锁。(详情请自行百度 wait notity notifyAll必须配合synchronized使用)
不懈努力,慢慢前行,变成自己喜欢的样子。
之前喜欢在有道云上做笔记,因为只有自己看,所以做的偷懒不好。希望换到简述上可以认真一点。水平不高,如果问题请留言指出,一起探讨。