Java线程-我想在序列中生成数字例如:1,2,3,4..以此类推(将只有2个线程)



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扩展线程{NumberGenerator num;

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

}

类SecondThreadClass扩展线程{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();
}

}

    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();
            }
        }

    }

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

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

他们是否每次只生成一个,或者如果线程1生成2个数字,然后线程2生成1个数字,等等…

?

使用一个静态int字段作为计数器,并以同步的方式访问它。

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

然后线程做:

while(...whatever..){
  System.out.print(getNextNumber());
}

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

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();
    }
}

您可以使用wait和notifyAll()来实现。但是使用标准的java并发类来实现它总是更好的

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++; 
    }
}

相关内容

  • 没有找到相关文章

最新更新