多线程|多线程 奇数偶数按序输出 自学自用

package t3;


import java.util.ArrayList;


/*计算偶数*/
public class MyThread2 extends Thread {


private ArrayList countList = new ArrayList();
int count = 0;


public MyThread2(ArrayList countList) {
this.countList = countList;
}


@Override
public void run() {
while (true) {
synchronized (countList) {
while (count % 2 != 0) {
try {
count += 1;
countList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
countList.add(count);
System.out.println("线程2(我打印的是偶数)-----" + countList.get(0));
countList.remove(0);
count += 1;
countList.notify();
}
}
}
}


========================================================


package t3;


import java.util.ArrayList;


/*计算奇数*/
public class MyThread1 extends Thread {


private ArrayList countList = new ArrayList();
int count = 0;


public MyThread1(ArrayList countList) {
this.countList = countList;
}


@Override
public void run() {
while (true) {
/*同步锁*/
synchronized (countList) {
while (count % 2 == 0) {
try {
count += 1;
countList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
countList.add(count);
System.out.println("线程1(我打印的是奇数)-----" + countList.get(0));
countList.remove(0);
count+=1;
countList.notify();
}
}
}
}







================================================



package t3;


import java.util.ArrayList;


public class ThreadTest2 {


public static void main(String[] args) {
ArrayList countList = new ArrayList();


new MyThread1(countList).start();
new MyThread2(countList).start();
}


}



【多线程|多线程 奇数偶数按序输出 自学自用】package t3;


import java.util.ArrayList;


public class ThreadTest2 {


public static void main(String[] args) {
ArrayList countList = new ArrayList();


new MyThread1(countList).start();
new MyThread2(countList).start();
}


}


    推荐阅读