Java之【线程通信】--标志位练习

这篇博客介绍了如何使用Java进行线程通信,通过标志位控制两个线程协作,一个打印1到52,另一个交替打印A到Z,确保打印顺序为12A34B...5152Z。文中提供了两种实现方式,一种直接实现,另一种利用标志位来协调线程间的操作,确保正确同步。

* 写两个线程,一个线程打印1-52,另一个线程答应字母A-Z。
* 打印顺序为12A34B56C……5152Z。通过使用线程之间的通信协调关系。

  • 注:分别给两个对象构造一个对象o,数字每打印两个或字母每打印一个就执行o.wait()。
  • 在o.wait()之前不要忘了写o.notify()

代码:

方法一:直接写

package Homework;

public class Test2 {
   
   
    public static void main(String[] args) {
        O o=new O();
        Threadnum threadnum=new Threadnum(o);
        Threadabc threadabc=new Threadabc(o);
        Thread thread=new Thread(threadnum);
        Thread thread2=new Thread(threadabc);
        thread.start();
        thread2.start();
    }
}

//资源类线程O
class O{
   
   
    public synchronized void num(){
        /*for(int i=1;i<=52;i++){
            System.out.print(i);
            if (i % 2 == 0) {
                this.notify();
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO 待完善
                    e.printStackTrace();
                }
            }*/
        for(int i=0;i<26;i++){  
            this.notify();
            for(int j=1+2*i;j<2*i+3;j++){
          
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值