题目:现在两个线程,可以操作同一个变量,实现一个线程对该变量加1,一个线程对该变量减1,实现交替,来10轮,变量初始值为零。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareData {
private int number = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void increment() throws Exception {
lock.lock();
try {
while (number != 0) {
condition.await();//this.wait();
}
++number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
condition.signalAll();//this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void decrement() throws Exception {
lock.lock();
try {
while (number == 0) {
condition.await();//this.wait();
}
--number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
condition.signalAll();//this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//========这种写法是最原始的写法使用了synchronized========
/*
public synchronized void increment() throws Exception
{
while(number != 0)
{
this.wait();
}
++number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
this.notifyAll();
}
public synchronized void decrement() throws Exception
{
while(number == 0)
{
this.wait();
}
--number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
this.notifyAll();
}
*/
}
/**
* 题目:现在两个线程,可以操作同一个变量,实现一个线程对该变量加1,一个线程对该变量减1,
* 实现交替,来10轮,变量初始值为零。
*
* @author admin
* 创建四个线程操作资源(高内聚,低耦合)
*/
public class ThreadDemo2 {
public static void main(String[] args) {
final ShareData sd = new ShareData();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(200);
sd.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "AA").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(300);
sd.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "BB").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(400);
sd.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "CC").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(500);
sd.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "DD").start();
}
}
在这个需要注意一个问题在共享对象的方法里 将if替换为while,解决虚假唤醒的问题。
最新评论
命令: nload
真是个良心站点哇,大公无私,爱了爱了
还可以直接搞一张映射表,存 uid | time | source_index, 第一次直接查对应的 time 选出前100, 第二次直接用 CompleteFuture 去分别用 source_in
干得漂亮,多个朋友堵条路
2021.2.2版本的不适用吧
现在还可以用么
激活码有用,感谢分享
激活码的地址打不开了