Multithreaded learning

Keywords: PHP REST Programming

Simple multithreaded applet code implementation:

1. Write a program to print out "I am a programmer" letter by letter by multithreading cooperation. The string has array storage of char type.

 

import static jodd.util.ThreadUtil.sleep;

public class CharNum {
     static String str = "i am a programmer";
     String[] str1 = str.split(" ");

     static char[] chars = null;
    static  volatile int len =0;

    public CharNum(){
        StringBuffer sb = new StringBuffer();
        for(int i =0;i< str1.length;i++){

          
            sb.append(str1[i]);

        }
       
        chars = sb.toString().toCharArray();
        len =  chars.length-1;
    }


     public  synchronized  void thread1(){

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

                 while(len>=0){
                     synchronized ("oo"){//Add a synchronization lock to multithreading
                         if(len>=0){
                             System.out.println("=======1 Output letters in sequence========"+chars[len]);
                             len--;
                         }

                     }

                     sleep(1000);

                 }

             }
         }).start();



     }

    public  synchronized  void thread2() {

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

                while (len >= 0) {
                    synchronized ("oo") {//Add a synchronization lock to multithreading
                        if (len >= 0) {
                            System.out.println("=======2 Output letters in sequence========" + chars[len]);
                            len--;
                        }

                    }

                    sleep(1000);

                }

            }
        }).start();

    }

     public static void main(String[] args){
        // CharNum cn = new CharNum();
        // System.out.println("================="+chars.length);

        CharNum cn = new CharNum();
         cn.thread1();
         cn.thread2();


     }



}

 

3. Tortoise and hare race
Tortoise and rabbit race: 2000 meters
Requirement:
(1) the speed of rabbit is 5 meters per 0.1 second, and the rest is 1 second per 20 meters.
(2) tortoise runs 2 meters every 0.1 seconds without rest;
(3) one runs to the end and the other doesn't!
Programming ideas:
Create an Animal class, inherit Thread, write a running abstract method, override the run method, and call the running method in the run method.
Create Rabbit rabbit class and Tortoise Tortoise class, inherit animal class
Two subclasses of (3) Rewrite the running method
(4) the third requirement of this question involves thread callback. You need to create a callback interface in the animal class and a callback object.

(I) create Animal

package com.Animal;

public abstract class Animal extends Thread{

    public int length = 200;


    public abstract void running();


    public void run (){
        super.run();
        while(length>0){

            running();
        }
    }

    //Declare an interface where a function needs to be dropped

    public static interface Calltoback{
        public void  win();
    }


    //Create interface object
    public Calltoback calltoback;

}

(II) create rabbit object

package com.Animal;


public class Rabbit extends Animal {

    public Rabbit(){

        setName("Rabbit");
    }


    @Override
    public void running() {
        //Rabbit speed
        int speet  = 5;
        length -=speet;

        System.out.println("The rabbit ran away."+speet+"Meters, from the end"+length+"Meter distance");

        if(length<=0){

            length = 0;
            System.out.println("The rabbit won");
            //Assign a value to the callback function to stop the tortoise running
            if (calltoback != null){
                 calltoback.win();
            }

        }


            try {
                if((2000-length)%20==0) {         //Every 20 meters, the rabbit will rest for 1 second.
                    this.sleep(1000);
                }else{
                    this.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


    }
}

(III) create turtle object

package com.Animal;

public class Tortoise extends Animal {

    public Tortoise(){

        this.setName("Tortoise");
    }


    @Override
    public void running() {

        int speet = 2;
        length -=speet;

        System.out.println("The tortoise has run"+speet+"Mi, and"+length+"Distance");

        if(length <= 0){
            length = 0;

            System.out.println("The tortoise won");
            //Let the rabbit stop running

            if(calltoback!=null){
                calltoback.win();
            }

        }

        try {
            sleep(100);  //Every 0.1 Run two meters in seconds.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

(IV) create callback function object

package com.Animal;

public class LetOnStop implements Animal.Calltoback {

    Animal an;

    //Get the animal object, which can be passed in the rabbit or tortoise object

    public LetOnStop(Animal an){
        this.an= an;

    }
    //Stop animal thread
    @Override
    public void win() {
       an.stop();
    }

}

(V) start multithreading

package com.Animal;

public class Test {

    public static void main(String[] args){
        Tortoise tt = new Tortoise();
        Rabbit rb = new Rabbit();

        //For the use of callback method, whoever calls the callback method first will not use the other one.
        LetOnStop ls1 = new LetOnStop(tt);
        //Let the tortoise value exist in the callback object of the rabbit to stop the tortoise
        rb.calltoback = ls1;

        LetOnStop ls2 = new LetOnStop(rb);
        tt.calltoback = ls2;

        tt.start();
        rb.start();



    }

}

Posted by ConcreteDJ on Thu, 31 Oct 2019 09:05:07 -0700