notify() 放在else代码块,没效果....
来源:7-7 交替打印

qq_改成什么名字呢_0
2019-10-18
package com.company;
public class Test1 {
private static int count =100;
private static volatile Integer dqCount = 0;
public static void main(String[] args) {
Thread thread = new Test1.Oushu();
Thread thread1 = new Test1.Qishu();
thread.start();
thread1.start();
}
static class Oushu extends Thread{
@Override
public void run() {
while(dqCount<=count){
synchronized (dqCount) {
// dqCount.notify(); //放在这里可以
if (dqCount % 2 == 0) {
System.out.println("偶数函数打印 :" + dqCount);
dqCount++;
} else {
try {
dqCount.notify();
dqCount.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
static class Qishu extends Thread{
@Override
public void run() {
while(dqCount<=count){
synchronized (dqCount) {
// dqCount.notify(); //放在这里可以
if (dqCount % 2 != 0) {
System.out.println("奇数函数打印 :" + dqCount);
dqCount++;
} else {
try {
dqCount.notify();
dqCount.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
写回答
1回答
-
你用的锁对象不是不可变的,会出问题。用new Object()作为锁,就可以了:
public class QQ { private static int count = 100; private static volatile Integer dqCount = 0; private static Object lock = new Object(); public static void main(String[] args) { Thread thread = new QQ.Oushu(); Thread thread1 = new QQ.Qishu(); thread.start(); thread1.start(); } static class Oushu extends Thread { @Override public void run() { while (dqCount <= count) { synchronized (lock) { // dqCount.notify(); //放在这里可以 if (dqCount % 2 == 0) { System.out.println("偶数函数打印 :" + dqCount); dqCount++; } else { try { lock.notify(); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } static class Qishu extends Thread { @Override public void run() { while (dqCount <= count) { synchronized (lock) { // dqCount.notify(); //放在这里可以 if (dqCount % 2 != 0) { System.out.println("奇数函数打印 :" + dqCount); dqCount++; } else { try { lock.notify(); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }
112019-10-18
相似问题