Use Runnable to achieve resource sharing

example

  • The reason is
    because only one object is instantiated using Runnable, and then Thread is used to encapsulate the object, and the operation is the attribute of this object, so this attribute can be modified together
  • code

public class Test {

    public static void main(String[] args) {

        Demo d = new Demo();
        Thread dd = new Thread(d,"DD1");
        Thread dd2 = new Thread(d,"DD2");
        Thread dd3 = new Thread(d,"DD3");
        dd.start();
        dd3.start();
        dd2.start();
    }

}

public class Demo implements Runnable{
    private int a = 30;
    @Override
    public void run() {

    for(int i = 10;i>1;i--){
    System.out.println( "At this time i is " +i+ "At this time a is " +(a++));
        }

    }

}

  • Part of the result of the run is
    when i is 10, then a is 30, then
    i is 9, then a is 31 , now
    i is 8, then a is 32 , then
    i is 7, then a is 33
    , then i is 6 When a is 34,
    i is 5, a is 35
    , i is 4, a is 36
    , i is 3, a is 37
    , i is 2, a is 39
    , and i is 10. When a is 40,
    i is 9, a is 41
    , i is 8, a is 42
    , i is 7, a is 43
    , i is 6, a is 44
    , and i is 5. a is 45,
    i is 4, a is 46
    , i is 10, a is 38
    , i is 9, a is 48
    , i is 3, a is 47
    , and i is 8. When a is 49,
    i is 2, a is 50
    , i is 7, a is 51
    , i is 6, a is 52
    , i is 5, a is 53
    , and i is 4. When a is 54,
    i is 3, a is 55
    , i is 2, and a is 56.
    The value of a is changed by the three of them together, so resource sharing is realized. For example, it can be used in the ticket selling system in China.

Leave a Comment

Your email address will not be published. Required fields are marked *