import java.util.ArrayList;
/*计算偶数*/
public class MyThread2 extends Thread {
private ArrayList<Integer> countList = new ArrayList<Integer>();
int count = 0;
public MyThread2(ArrayList<Integer> 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<Integer> countList = new ArrayList<Integer>();
int count = 0;
public MyThread1(ArrayList<Integer> 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<Integer> countList = new ArrayList<Integer>();
new MyThread1(countList).start();
new MyThread2(countList).start();
}
}
package t3;
import java.util.ArrayList;
public class ThreadTest2 {
public static void main(String[] args) {
ArrayList<Integer> countList = new ArrayList<Integer>();
new MyThread1(countList).start();
new MyThread2(countList).start();
}
}