0
点赞
收藏
分享

微信扫一扫

2个线程顺序工作

小猪肥 2022-11-15 阅读 12

2个线程,一个线程先写,然后另外一个线程读,以此循环。

static int i = 8;
static Object obj = new Object();
public static void main(String[] args) throws InterruptedException {
Thread read = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 100; j++) {
synchronized (obj) {
System.out.println("read:" + i);

obj.notify();

try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
}
});
Thread write = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 100; j++) {
synchronized (obj) {
i = j;
System.out.println("write:" + i);

obj.notify();

try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
write.setName("write");
read.setName("read");

write.start();
Thread.sleep(10);
read.start();
}

 

举报

相关推荐

0 条评论