1. 最容易理解版本
public class 多线程循环打印2 {
public static int count = 3;
public static int end = 100;
public static int start = 0;
public static Object Lock = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
synchronized (Lock) {
while (start <= end) {
while (start % count != 0) {
try {
Lock.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
if (start <= end) {
System.out.println("0:" + start);
}
start++;
Lock.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
synchronized (Lock) {
while (start <= end) {
while (start % count != 1) {
try {
Lock.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
if (start <= end) {
System.out.println("1: " + start);
}
start++;
Lock.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
synchronized (Lock) {
while (start <= end) {
while (start % count != 2) {
try {
Lock.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
if (start <= end) {
System.out.println("2:" + start);
}
start++;
Lock.notifyAll();
}
}
}
}).start();
}
}
2. 封装
public class 多线程循环打印 {
public static int count = 3;
public static int end = 100;
public static int start = 0;
public static Object Lock = new Object();
public static void main(String[] args) {
for (int i = 0; i < count; i++) {
new Thread(new MyRnna(i)).start();
}
}
public static class MyRnna implements Runnable{
private int order;
public MyRnna(int order){
this.order = order;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (start < end) {
synchronized(Lock){
while (start % count != order) {
try {
Lock.wait();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if(start <= end)
System.out.println(order + ": " + start);
start++;
Lock.notifyAll();
}
}
}
}
}