两个线程交替运行
public class WaitAndNotify {
public static Object lock = new Object ( ) ;
static class ThreadA implements Runnable {
@Override
public void run ( ) {
synchronized ( lock) {
for ( int i = 0 ; i < 5 ; i++ ) {
try {
System. out. println ( "ThreadA: " + i) ;
lock. notify ( ) ;
lock. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
lock. notify ( ) ;
}
}
}
static class ThreadB implements Runnable {
@Override
public void run ( ) {
synchronized ( lock) {
for ( int i = 0 ; i < 5 ; i++ ) {
try {
System. out. println ( "ThreadB: " + i) ;
lock. notify ( ) ;
lock. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
lock. notify ( ) ;
}
}
}
public static void main ( String[ ] args) throws InterruptedException {
new Thread ( new ThreadA ( ) ) . start ( ) ;
Thread. sleep ( 1000 ) ;
new Thread ( new ThreadB ( ) ) . start ( ) ;
}
}
两个线程交替打印0-10
package test;
public class Signal {
private static volatile int signal = 0 ;
private static Object lock = new Object ( ) ;
static class ThreadA implements Runnable {
@Override
public void run ( ) {
while ( signal < 10 ) {
if ( signal % 2 == 0 ) {
System. out. println ( "ThreadA:" + signal) ;
synchronized ( lock) {
signal++ ;
}
}
}
}
}
static class ThreadB implements Runnable {
@Override
public void run ( ) {
while ( signal < 10 ) {
if ( signal % 2 == 1 ) {
System. out. println ( "ThreadB:" + signal) ;
synchronized ( lock) {
signal++ ;
}
}
}
}
}
public static void main ( String[ ] args) throws InterruptedException {
new Thread ( new ThreadA ( ) ) . start ( ) ;
Thread. sleep ( 1000 ) ;
new Thread ( new ThreadB ( ) ) . start ( ) ;
}
}