一、两个线程轮流打印数字。
加锁实现:
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();
}
}