问题描述:
多线程打印20个偶数20个奇数为一组交替打印;
/**
* 多线程打印
* 先打印20个偶数在打印20个奇数依次循环交替
* @author dongfen
*
*/
public class EOdd {
public static void main(String[] args) {
Num1 num = new Num1(1000);
Thread edd = new Thread(new EddThread1(num));
edd.setName("edd");
edd.start();
Thread odd = new Thread(new OddThread1(num));
odd.setName("odd");
odd.start();
}
}
class Num1{
private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
// TODO Auto-generated method stub
return 0;
}
};
private int max;
public Num1(int max){
this.max = max;
}
public synchronized void printEdd(){
for(int i = 0; i< max;i+=2){
System.out.println(Thread.currentThread().getName() + " " + i);
threadLocal.set(threadLocal.get()+1);
if(threadLocal.get() % 20 == 0){
waitFor();
}
}
notifyAllThread();
}
private void notifyAllThread() {
try {
this.notifyAll();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void waitFor() {
this.notifyAll();
try {
this.wait();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printOdd(){
for(int i = 1; i< max;i+=2){
System.out.println(Thread.currentThread().getName() + " " + i);
threadLocal.set(threadLocal.get()+1);
if(threadLocal.get() % 20 == 0){
waitFor();
}
}
notifyAllThread();
}
}
class EddThread1 implements Runnable{
private Num1 num;
public EddThread1(Num1 num){
this.num = num;
}
public void run() {
this.num.printEdd();
}
}
class OddThread1 implements Runnable{
private Num1 num;
public OddThread1(Num1 num){
this.num = num;
}
public void run() {
this.num.printOdd();
}
}
参考资料地址: Java 多线程 子线程 交替打印 奇偶数