public static void main(String[] args) {
Counting c=new Counting();
Thread t1=new Thread(c);
Thread t2=new Thread(c);
t1.setName("AISong");
t2.setName("KobeSong");
t1.start();
t2.start();
}
}
class Counting implements Runnable {
int i = 0;
@Override
public void run() {
while (true) {
synchronized (this) {
notify();//notify()/notifyAll() 应用在同步代码块中,唤醒一个/所有线程
if (i < 24) {
i++;
System.out.println(Thread.currentThread().getName() + ":" + i);
} else
break;
try {
wait();//应用在同步代码块中,释放当前锁
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
AISong:1
KobeSong:2
AISong:3
KobeSong:4
AISong:5
KobeSong:6
AISong:7
KobeSong:8
AISong:9
KobeSong:10
AISong:11
KobeSong:12
AISong:13
KobeSong:14
AISong:15
KobeSong:16
AISong:17
KobeSong:18
AISong:19
KobeSong:20
AISong:21
KobeSong:22
AISong:23
KobeSong:24