一、两个线程轮流打印数字。
加锁实现:
package lianxi;
/*
* 用锁实现两个线程轮流打印1——100
*/
public class Print1TO100TwoThread {
private Object lock = new Object();
private int i = 0;
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
while (i <= 100) {
synchronized (lock) {try {
if (i > 100)
break;
System.out.println("threadA:" + (i++));
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} });
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
while (i <= 100) {
synchronized (lock) {try {
if (i > 100)
break;
System.out.println("threadB:" + (i++));
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
public void startTwoThread() throws InterruptedException {
threadA.start();
Thread.sleep(20);
threadB.start();
}
public static void main(String[] args) throws InterruptedException {
new Print1TO100TwoThread().startTwoThread();
}}
用锁效率太低,用一个变量来控制打印的顺序。
package lianxi;
/*
* 用两个线程轮流打印1——10;用所实现效率太低,用变量来控制
*/
public class PrinntNumTwoThread { private volatile int num = 0;
private volatile boolean flag = false;
Thread threadA = new Thread(new Runnable() {@Override
public void run() {
while (true) {
if (num > 10)
return;
if (!flag) {
System.out.println("threadA-->" + ":" + (num++));
flag = !flag;
}
}
} });
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (num > 10)
return;
if (flag) {
System.out.println("threadB-->" + ":" + (num++));
flag = !flag;
}
}
} });
public void startTwoThread() {
threadA.start();
threadB.start();
} public static void main(String[] args) {
new PrinntNumTwoThread().startTwoThread();
}
}
二、那么如果要实现三个线程轮流打印1-100的数字呢?
package lianxi;
public class PrintNumThreeThread {
private volatile int i = 0;
private volatile int flag = 0;
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (i > 100)
return;
if (flag == 0) {
System.out.println("threadA->" + ":" + (i++));
flag = 1;
}
}
} });
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (i > 100)
return;
if (flag == 1) {
System.out.println("threadB->" + ":" + (i++));
flag = 2;
}
}
} });
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (i > 100)
return;
if (flag == 2) {
System.out.println("threadC->" + ":" + (i++));
flag = 0;
}
}
}
});
public void startThreeThread() {
threadA.start();
threadB.start();
threadC.start();
} public static void main(String[] args) {
new PrintNumThreeThread().startThreeThread();
}}
【Java n个线程轮流打印数字的问题】
推荐阅读
- 代码狂魔|实战证明java中的两把锁ReentrantLock与synchronized的系统调用
- 进程通信方式
- 解决方案|大文件拆分方案的java实践
- 多线程编程(1)(共享内存与锁)
- Java|多线程编程(二)——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)
- 一道面试题(多个线程按顺序输出)
- 多线程|java多线程实现奇偶数输出
- 面试题--三个线程循环打印ABC 10次(另类解决方法)
- 用信号量(互斥锁)实现两个线程交替打印