实现两个线程交替打印1~100的数

要点总结:

  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();
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值