实现两个线程交替输出奇数偶数:
synchronized
public void printNumber() {
int[] count = {1};
String lock = "lock";
Thread oddThread = new Thread(() -> {
synchronized (lock) {
while(count[0] < 100) {
while(count[0] %2 != 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + count[0]);
count[0]++;
lock.notifyAll();
}
}
});
Thread evenThread = new Thread(() -> {
synchronized (lock) {
while(count[0] < 100) {
while(count[0] %2 != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + count[0]);
count[0]++;
lock.notifyAll();
}
}
});
oddThread.start();
evenThread.start();
}
ReentrantLock
public void printNumber() {
ReentrantLock reentrantLock = new ReentrantLock();
Condition condition = reentrantLock.newCondition();
int[] count = {1};
Thread oddThread = new Thread(() -> {
reentrantLock.lock();
try {
while (count[0] < 100) {
while (count[0] % 2 != 1) {
condition.await();
}
System.out.println(Thread.currentThread().getName() + ":" + count[0]);
count[0] ++;
condition.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
});
Thread evenThread = new Thread(() -> {
reentrantLock.lock();
try {
while (count[0] < 100) {
while (count[0] % 2 != 0) {
condition.await();
}
System.out.println(Thread.currentThread().getName() + ":" + count[0]);
count[0] ++;
condition.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
});
oddThread.start();
evenThread.start();
}
网友评论