java多线程之synchronized
public class MultiThreadPrint {
private final int threadNum;
private final int printTo;
private int count = 0;
private final Object lock = new Object();
public static void main(String[] args) {
new MultiThreadPrint(5, 100).threadsPrint();
}
public MultiThreadPrint(int threadNum, int printTo){
if(threadNum < 1 || printTo < 1 || threadNum > printTo){
throw new RuntimeException("错误参数");
}
this.threadNum = threadNum;
this.printTo = printTo;
}
class PrintThread implements Runnable {
int flag;
public PrintThread (int flag){
this.flag = flag;
}
@Override
public void run() {
synchronized (lock){
while(true){
if(count == printTo){
lock.notifyAll();
return;
}else if(count % threadNum == flag){
System.out.println(Thread.currentThread().getName() + " " + ++count);
lock.notifyAll();
}else{
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
public void threadsPrint(){
for (int i = 0; i < threadNum; i++) {
new Thread(new PrintThread(i), "thread---"+i).start();
}
}
}