package test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread("线程1"){
public void run() {
try {
for(int i=0;i<10;i++){
new Sum().run1();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
new Thread("线程2"){
public void run() {
try {
for(int i=0;i<10;i++){
new Sum().run2();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
class Sum {
int i=1;
//public static Object obj=new Object();
Class obj=this.getClass();
int flg=1;
public void run1() throws InterruptedException{
System.out.print("线程1.。。。");
synchronized (obj) {
while(flg!=1){
obj.wait();
}
if(i<11){
System.out.println(i);
i++;
}
System.out.println(i);
flg=2;
obj.notifyAll();
}
}
public void run2() throws InterruptedException{
System.out.println("线程2");
synchronized (obj) {
while(flg!=2){
obj.wait();
}
if(i<11){
System.out.println(i);
i++;
}
flg=1;
obj.notifyAll();
}
}
} |
|