方法一:
public class Print {
boolean flag=true;
public synchronized void printA(int i){
if(flag==false){
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
} System.out.print(i+",");
flag=false;
notify();
}
public synchronized void printB(int i){
if(flag==true){
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}System.out.print(i+",");
flag=true;
notify();
}
}
class A extends Thread{
private Print p;
public A(Print p){
this.p=p;
}
@Override
public void run(){
for(int i=1;i<=10;i++){
p.printA(i);
}
}
}
class B extends Thread{
private Print p;
public B(Print p){
this.p=p;
}
@Override
public void run(){
for(int i=10;i>=1;i--){
p.printB(i);
}
}
}
public class dsd {
public static void main(String args[]){
Print p=new Print();
A a=new A(p);
B b=new B(p);
a.start();
b.start();
}
}
方法二:
public class Work6 {
public static void main(String[] args) {
Object obj = new Object();
A a = new A(obj);
B b = new B(obj);
a.start();
b.start();
}
}
class A extends Thread {
Object obj;
public A(Object obj) {
super();
this.obj = obj;
}
//正序打印
@Override
public void run() {
synchronized (obj) {
for (int i = 1; i <= 10; i++) {
System.out.print(i + ",");
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class B extends Thread {
Object obj;
public B(Object obj) {
super();
this.obj = obj;
}
//逆序打印
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
for (int i = 10; i > 0; i--) {
System.out.print(i + ",");
obj.notify();
if (i > 0) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}