要点总结:
1.熟练使用多线程创建与调用
2.熟练使用同步代码块
3.使用wait()和notify方法
步骤如下:
1)创建CounterRunner子类,实现Runnable接口,实现run()方法
public class CounterRunner implements Runnable{
private int count; // 定义计数器
@Override
public void run() {
for (int i = 0; i <50 ; i++) { // 因为是两个线程输出100,说以各执行50次
synchronized(""){ // 通过字符串常量充当锁对象
"".notify(); // 通知另一个线程结束wait等待,但是另一个线程只是进入了等锁状态
count++; // 计数器加1
System.out.println(Thread.currentThread().getName()+" "+count); // 打印输出
try {
if(count != 100 && count != 101){ // 最后一次循环则不进行wait等待
"".wait(); // 当前线程进入wait等待,释放锁,另一个等待锁的线程进入运行状态
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
2)在main方法中创建线程,并进行测试
public class CounterTest {
public static void main(String[] args) { // 线程一定要在主方法中测试
/**
* 实现两个线程交替打印1~100的数
*/
Runnable counterRunner = new CounterRunner();
Thread thread1 = new Thread(counterRunner);
thread1.setName("线程1号");
thread1.start();
Thread thread2 = new Thread(counterRunner);
thread2.setName("线程2号");
thread2.start();
}
}