使用多线程打印字母和数字

问题描述 投票:0回答:3

我刚开始学习线程并且很新。我正在尝试一个接一个地打印字母和数字。我已经使用一个标志同步它们但没有用。

公共类Alphabets {

public static void main(String[] args) {

          AN an= new AN(false);

          Thread t1=new Thread(new Runnable() {

            @Override
            public void run() {

                try {

                    an.Alpha();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });


          Thread t2= new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    an.numbers();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });


          t1.start();
          t2.start();
}

}

AN类{

boolean flag;

AN(boolean flag)
{
    this.flag=flag;
}
synchronized void Alpha() throws InterruptedException
{
    if(flag==false)
    {
    for(char i='A'; i<='Z';i++)
    {
        System.out.println(+i);
        notifyAll();
        flag=true;
    }
    }
    else
    {
        wait();
    }

}

synchronized void numbers() throws InterruptedException
{
    if(flag==true)
    {
    for(int i=1;i<=26;i++)
    {
        System.out.println(+i);
        notifyAll();
        flag=false;
    }
    }
    else
    {
        wait();
    }
}

}

我想要的输出是:a1b2c3d4 ....

我的控制台输出是:abcd ... 1234 ...

任何人都可以指出错误,因为我无法同步这两个线程。

java multithreading synchronization thread-synchronization
3个回答
0
投票

更改类AN以检查while循环中的标志。

public class AN {
  boolean flag;

  AN(boolean flag) {
    this.flag = flag;
  }

  synchronized void Alpha() throws InterruptedException {

    for(char i = 'A'; i <= 'Z'; i++) {
      while(flag == true) {
        wait();
      }
      System.out.println(i);
      notifyAll();
      flag = true;
    }
  }

  synchronized void numbers() throws InterruptedException {

    for(int i = 1; i <= 26; i++) {
      while(flag == false) {
        wait();
      }
      System.out.println(i);
      notifyAll();
      flag = false;
    }
  }

0
投票

那么,你想要的是或多或少的流水线,因此线程需要知道何时允许它们工作。

因此,我使用队列来等待一个线程上的输入,并等待它在另一个线程中设置。

AN类:

import java.util.concurrent.BlockingQueue;

class AN
{

    BlockingQueue<Boolean> input;

    BlockingQueue<Boolean> output;

    AN(BlockingQueue<Boolean> input, BlockingQueue<Boolean> output)
    {

        this.input = input;
        this.output = output;
    }

    void Alpha() throws InterruptedException
    {
        for (char i = 'a'; i <= 'z'; i++) {
            input.take();
            System.out.print(i);
            output.put(Boolean.TRUE);

        }
    }

    void numbers() throws InterruptedException
    {
        for (int i = 1; i <= 26; i++) {
            input.take();
            System.out.print(i);
            output.put(Boolean.TRUE);
        }

    }

}

班级考试(或你的主要考试):

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Test
{

    public static void main(String[] args) throws InterruptedException
    {

        BlockingQueue<Boolean> input = new LinkedBlockingQueue<>();
        BlockingQueue<Boolean> output = new LinkedBlockingQueue<>();

        AN an1 = new AN(output, input);
        AN an2 = new AN(input, output);
        output.add(Boolean.TRUE);

        Thread t1 = new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                try {
                    an1.Alpha();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                try {
                    an2.numbers();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

        t1.start();
        t2.start();

    }
}

产出:a1b2c3d4e5f6g7h8i9j10k11l12m13n14o15p16q17r18s19t20u21v22w23x24y25z26


0
投票

您可以通过使用BlockingQueue和Object的wait和notify方法来实现此目的。

public class AlphaNum {
    public static void main(String[] args) throws InterruptedException {


    BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);

    AtomicBoolean flag = new AtomicBoolean(Boolean.TRUE);

    Object lock = new Object();

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                for(int i=1;i<=26;i++){
                        synchronized (lock){
                            while (flag.get()){
                                lock.wait();
                            }
                            System.out.print(i);
                            flag.set(Boolean.TRUE);
                            lock.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                for(char c='A';c<='Z';c++){
                    synchronized (lock){
                        while (!flag.get()){
                            lock.wait();
                        }
                        System.out.print(c);
                        flag.set(Boolean.FALSE);
                        lock.notify();
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });


    t1.start();
    t2.start();

    }
}

上面的代码打印a1b2c3d4 ....... z26

© www.soinside.com 2019 - 2024. All rights reserved.