2019/03/16 13:31

# 背景

通过N个线程顺序循环打印从0至100，如给定N=3则输出:
.....


两个线程交替打印0~100的奇偶数：



# 两线程奇偶数打印

public class 交替打印奇偶数 {
static int value = 0;
@Override
public void run() {
while (value <= 100){
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
}
}


# N个线程循环打印

public class 老司机1 implements Runnable {

private static final Object LOCK = new Object();
/**
* 当前即将打印的数字
*/
private static int current = 0;
/**
* 当前线程编号，从0开始
*/
/**
* 线程数量
*/
/**
* 打印的最大数值
*/
private int maxInt;

this.maxInt = maxInt;
}

@Override
public void run() {
while (true) {
synchronized (LOCK) {
// 判断是否轮到当前线程执行
if (current > maxInt) {
break;
}
try {
// 如果不是，则当前线程进入wait
LOCK.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
// 最大值跳出循环
if (current > maxInt) {
break;
}
current++;
// 唤醒其他wait线程
LOCK.notifyAll();
}
}
}

public static void main(String[] args) {
int max = 100;
for (int i = 0; i < threadCount; i++) {
}
}
}



static int result = 0;
public static void main(String[] args) throws InterruptedException {
int N = 3;
final Semaphore[] syncObjects = new Semaphore[N];
for (int i = 0; i < N; i++) {
syncObjects[i] = new Semaphore(1);
if (i != N-1){
syncObjects[i].acquire();
}
}
for (int i = 0; i < N; i++) {
final Semaphore lastSemphore = i == 0 ? syncObjects[N - 1] : syncObjects[i - 1];
final Semaphore curSemphore = syncObjects[i];
final int index = i;

public void run() {
try {
while (true) {
lastSemphore.acquire();
System.out.println("thread" + index + ": " + result++);
if (result > 100){
System.exit(0);
}
curSemphore.release();
}
} catch (Exception e) {
e.printStackTrace();
}

}
});
}
}


8 评论
52 收藏
9