Java Thread - men ketma-ketlikdagi raqamlarni yaratmoqchiman: 1,2,3,4 ... shuning uchun (faqat 2 ta mavzu bo'ladi)

Java Thread - men ketma-ketlikda raqamlarni yaratmoqchiman: 1,2,3,4 ... (faqat 2 ta mavzu bo'ladi) 1-chi nuqta o/p 1, ikkinchi tirajli o/p 2 bo'ladi, yana 1 thread o/p 3 va shunga o'xshash bo'ladi, u 10 yoki upto n qadar bo'lishi mumkin, faqat mantiqiy qabul qilish istasang, menga yordam bering: |

Quyida men buni amalga oshirishga urinishim kerak, lekin u ishlamayapti, shuni bilamanki, kutish() va xabar berish usullari haqida xabar berishi mumkin, ammo ularni ishlatishning to'g'ri yo'lini tushunib bo'lmaydi!

sinf NumberGenerator {     static int = 0;

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

}

sinf BirinchiThreadClass mavzuni kengaytiradi {     NumberGenerator raqami;

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

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

}

}

class SecondThreadClass mavzuni kengaytiradi {     NumberGenerator raqami;

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

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

}

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

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

}

0
Siz allaqachon sinab ko'rgan kodni yuborishingiz mumkinmi?
qo'shib qo'ydi muallif PDStat, manba
Bir vaqtning o'zida bir biriga ega bo'lgan barcha nuqtalar mustaqil ishni bir vaqtning o'zida bajarishga imkon berishdir. Agar siz ushbu talabga amal qilsangiz, u vazifalar bir-biriga bog'liq bo'lgani uchun ishlamaydi.
qo'shib qo'ydi muallif Peter Lawrey, manba

5 javoblar

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


    }
1
qo'shib qo'ydi
Siz threadning ishlash uslubini chaqirasiz va boshlamaysiz, ba'zi usullarni qo'lda chaqirish bilan bir xil. Savol - ikkita ikkita zarrachali ketma-ketlikni bosib chiqarish
qo'shib qo'ydi muallif coder, manba

Ular har safar faqat bitta ishlab chiqarishni amalga oshirishlari kerakmi yoki agar thread1 2 raqamni yaratganida OK bo'lsa, unda ip 2 1 raqamni va boshqalarni ishlab chiqaradi ...?

Taymer sifatida harakatlanadigan statik int maydonidan foydalaning va sinxronlashtirilgan tarzda foydalaning.

static int counter = 0;

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

Keyin iplar:

while(...whatever..){
  System.out.print(getNextNumber());
}
0
qo'shib qo'ydi
Men sizning mantiqanizni o/p ni bosish bilan sinab ko'rdim: 1-banddan: 0 dan 2-banddan: 1
qo'shib qo'ydi muallif Soumyaansh, manba
Men n-n-sonli tartibini bosib chiqarishni xohlayman, lekin nusha faqat 1,2 ni bekitish() va xabardor qilish uchun() bir marta tsilindrni bosib chiqarish va kutish() holatiga tushib qolsa, va o'z-o'zidan kutish() holatiga o'tadi, tishli bosma 3 va hokazo ..
qo'shib qo'ydi muallif Soumyaansh, manba
Ha, siz xohlagan narsa emasmi?
qo'shib qo'ydi muallif kgautron, manba

Har bir zarrachani raqamlarni quyidagicha yaratishingiz mumkin:

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

bir vaqtning o'zida to'plash va tartiblashtirishga qo'shing.

0
qo'shib qo'ydi
bu javob berishga qodir bo'lmagan intervyuda so'radi ... Kecha men hal qilishni tushunishga harakat qilaman:
qo'shib qo'ydi muallif Soumyaansh, manba
@peter lawrey Xristian peter sharhingiz uchun tashakkur Ha Yo'q, siz nima gapirayotganingizni bilaman, lekin suhbatdoshga qarshi da'vo qila olmayman: P Mendan bu haqda so'radi, shuning uchun ham javob berishim kerak edi :(
qo'shib qo'ydi muallif Soumyaansh, manba

bunga uslubiy to'siq yordamida erishish mumkin, to'siq yaratadi va bir vaqtning o'zida ikkita zarrachalar bitta raqamni chiqaradi va har ikkala raqamni bosadi

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();
    }
}
0
qo'shib qo'ydi

Kutish va notifyAll() yordamida foydalanishingiz mumkin. Lekin bunga erishish uchun standart java-parallel sinflarni ishlatish har doim ham yaxshiroqdir

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++; 
    }
}
0
qo'shib qo'ydi