0

Java 线程 - 我想按顺序生成数字,例如:1,2,3,4...(只有 2 个线程)第一个线程 o/p 将是 1,第二个线程 o/p 将是 2,再次是第一个线程 o/p 将是 3 等等,它最多可以是 10 或最多 n 个数字,只要想得到逻辑,请帮助我:|

下面是我的尝试,但它不起作用我知道肯定会有 wait() 和 notify() 方法,但无法弄清楚使用它们的正确方法!

类 NumberGenerator { static int number = 0;

synchronized public int numGenerator()
{
    for(int i=0;i<20;i++)
    {
        System.out.println(i);
        number=i;
    }
    return number;
}

}

类 FirstThreadClass 扩展 Thread { NumberGenerator num;

FirstThreadClass(NumberGenerator num)
{
    this.num = num;
}

public void run()
{
    System.out.println("i am from 1st thread :"+num.numGenerator());

}

}

类 SecondThreadClass 扩展 Thread { NumberGenerator num;

SecondThreadClass(NumberGenerator num)
{
    this.num = num;
}

public void run()
{
    System.out.println("i am from 2nd thread :"+num.numGenerator());
}

}

公共类 ThreadTesting { public static void main(String[] args) {

    FirstThreadClass ftc = new FirstThreadClass(new NumberGenerator());
    SecondThreadClass stc = new SecondThreadClass(new NumberGenerator());
    ftc.start();
    stc.start();
}

}

4

5 回答 5

1
    class NumberGenerator
    {
        static int counter = 0;

        public synchronized int getNextNumber()
        {
            return counter++;
        }


    }
    class FirstThreadClass
        extends Thread
    {
        NumberGenerator num;

        FirstThreadClass(NumberGenerator num)
        {
            this.num = num;
        }

        public void run()
        {
            System.out.println("i am from 1st thread :" + num.getNextNumber());

        }


    }
    class SecondThreadClass
        extends Thread
    {
        NumberGenerator num;

        SecondThreadClass(NumberGenerator num)
        {
            this.num = num;
        }

        public void run()
        {
            System.out.println("i am from 2nd thread :" + num.getNextNumber());
        }


    }

    public class ThreadTesting
    {
        public static void main(String[] args)
        {
            FirstThreadClass ftc = new FirstThreadClass(new NumberGenerator());
            SecondThreadClass stc = new SecondThreadClass(new NumberGenerator());
            for (int k = 0; k < 10; k++)
            {
                ftc.run();
                stc.run();
            }
        }


    }
于 2013-01-21T09:14:41.730 回答
0

您可以让每个线程生成数字,如下所示:

Thread 1: 1, 3, 5, 7, 9, ...
Thread 2: 2, 4, 6, 8, 10, ...

添加到并发集合并随后排序。

于 2011-10-28T07:54:29.183 回答
0

他们是否必须每次只生成一个,或者如果线程1生成2个数字,然后线程2生成1个数字等等......可以吗?

使用将充当计数器的静态 int 字段,并以同步方式访问它。

static int counter = 0;

public synchronized int getNextNumber(){
  return counter++;
} 

然后线程做:

while(...whatever..){
  System.out.print(getNextNumber());
}
于 2011-10-28T07:54:31.500 回答
0

您可以使用循环屏障来实现这一点,创建一个屏障,一旦两个线程生成一个数字,每个打印两个数字

class ThreadTest {

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
        @Override
        public void run() {
            System.out.println(oddNumberGenerator.result);
            System.out.println(evenNumberGenerator.result);
        }
    });

    private NumberGenerator oddNumberGenerator = new NumberGenerator(1,11,2);
    private NumberGenerator evenNumberGenerator = new NumberGenerator(2,10,2);

    public void generateSeries(){
        oddNumberGenerator.generateNumbers();
        evenNumberGenerator.generateNumbers();
    }


    class NumberGenerator {
        private Thread thread;
        private int result;

        private NumberGenerator(final int initialValue, final int maxValue,
                                final int stepSize) {
            this.thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = initialValue; i <= maxValue; i = i + stepSize) {
                        try {
                            result = i;
                            cyclicBarrier.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

        public void generateNumbers() {
            thread.start();
        }
    }


    main(String[] args){
       new ThreadTest().generateSeries();
    }
}
于 2013-12-31T08:23:30.463 回答
0

You can achieve using wait and notifyAll() . But it is always better to use standard java concurrent classes to achieve it

public class PrintAlternateValues {
    public static void main(String[] args) {

        final NumberValue number = new NumberValue();
        final Object lockObject = new Object();
        new Thread(){

            private NumberValue n  = number;
            @Override
            public void run() {
                synchronized (lockObject) {
                    while(n.getValue() < n.getEndPoint()){
                        while(n.isToggle()){
                            try{
                                lockObject.wait();
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }

                        n.incrementValue();
                        System.out.println(getName() + " printing "+n.getValue());
                        n.setToggle(true);
                        lockObject.notifyAll();
                    }
                }
            }
        }.start();

        new Thread(){

            private NumberValue n  = number;
            @Override
            public void run() {
                synchronized (lockObject) {
                    while(n.getValue() < n.getEndPoint()){
                        while(!n.isToggle()){
                            try{
                                lockObject.wait();
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }

                        n.incrementValue();
                        System.out.println(getName() + " printing "+n.getValue());
                        n.setToggle(false);
                        lockObject.notifyAll();
                    }
                }
            }
        }.start();
    }
}

class NumberValue {
    private int value;
    private boolean toggle = true;
    private int endPoint = 10;

    public int getEndPoint() {
        return endPoint;
    }

    public void setEndPoint(int endPoint) {
        this.endPoint = endPoint;
    }

    public boolean isToggle() {
        return toggle;
    }

    public void setToggle(boolean toggle) {
        this.toggle = toggle;
    }

    public  int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public synchronized void incrementValue(){
        this.value++; 
    }
}
于 2015-06-27T07:43:01.540 回答