This is the 27th day of my participation in the More Text Challenge. For more details, see more text Challenge


Related articles

Java Multithreading summary: Java multithreading


preface

Static proxy belongs to the proxy pattern in the design pattern. On the contrary, there is a dynamic proxy, this article does not expand, interested in Google research research. Inheriting Thread is also a kind of static proxy, so learning about static proxies here helps us learn about multithreading.

One, static proxy

  • Actual case: buy a house

    • Buyers are I
    • Purchase agent agent
    • The common act of buying a house
  • Code implementation case:

class MyI implements BuyHouse {

    // For me, all I have to do is take the money and sign
    @Override
    public void Buy(a) {
        System.out.println("A million dollars, sign the contract, the house is mine!"); }}class Agent implements BuyHouse{
    private BuyHouse buyHouse;
    
    public Agent(BuyHouse buyHouse){
        this.buyHouse = buyHouse;
    }

    // First help me to prepare the contract and other materials
    public void work1(a){
        System.out.println("Prepare the contract and other materials ~");
    }
    // Take me to the housing authority to go through the formalities
    public void work2(a){
        System.out.println("Take the client to the procedure ~");
    }

    // The agent takes my money, he has to help me prepare the purchase materials, walk me through the purchase process, etc
    @Override
    public void Buy(a) {
        work1();
        work2();
        // The client buys a housebuyHouse.Buy(); }}Copy the code
  • The execution result is as follows:

  • Conclusion:
    • In essence, it is equivalent to separating the business and reducing the coupling of the process. The ultimate goal of both the intermediary and me is to buy a house. I only focus on the business of buying a house and do not need to manage other businesses, while the intermediary needs to prepare materials, prepare contracts and take me to the housing administration Bureau.

2. Thread stop

  • There are three ways to stop a running thread in Java:

    • Use the exit flag to cause the thread to terminate normally, which is when the run method completes.
    • Use the stop method to forcibly terminate a thread, but it is not recommended because stop, like suspend and resume, is an expired method.
    • Use the interrupt method to interrupt the thread.
  • Use flag bits to stop a thread:

/** * Use status flags to stop threads */
public class TestThreadDemo01 implements Runnable{
    public static void main(String[] args) throws Exception {
        TestThreadDemo01 threadDemo01 = new TestThreadDemo01();
        new Thread(threadDemo01).start();
        for (int i=0; i<1000; i++){ System.out.println("Main thread"+i);
            if (i==900){
                threadDemo01.stop();
                System.out.println("The thread has stopped!);
                break; }}}// Status tag
    private boolean flag = true;

    @Override
    public void run(a) {
        int i = 0;
        while (flag){
            System.out.println("Threads!+ (i++)); }}public void stop(a){
        this.flag = false; }}Copy the code
  • The execution result is as follows:

3. Thread sleep (sleep)

  • Conclusion:

    • Sleep (time) specifies how many milliseconds the current thread is blocking;
    • Sleep An exception InterruptedException exists
    • When the sleep time is up, the thread enters the ready state
    • Sleep can simulate network latency, countdown, and more.
    • Each object has a lock, and sleep does not release the lock
  • Code examples:

/**
 * 线程休眠 sleep
 */
public class TestThreadSleep implements Runnable{
    public static void main(String[] args) {
        TestThreadSleep th1 = new TestThreadSleep();
        new Thread(th1).start();
    }

    @Override
    public void run(a) {
        // Simulate the countdown
        for (int i=10; i>0; i--){try {
                Thread.sleep(1000);
            } catch(InterruptedException e) { e.printStackTrace(); } System.out.println(i); }}}Copy the code
  • The execution result is as follows:

4. Yield to threads

  • Conciliation allows the currently executing thread to pause, but not block

  • Changes the thread from the running state to the ready state

  • Let CPU rescheduling, comity may not succeed! Look at the CPU mood.

  • Code examples:

/** * Thread comity */
public class TestThreadComity implements Runnable{
    public static void main(String[] args) {
        TestThreadComity th = new TestThreadComity();
        new Thread(th,Thread 1 "").start();
        new Thread(th,Thread 2 "").start();
    }

    @Override
    public void run(a) {
        System.out.println(Thread.currentThread().getName()+"Execution!");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"End execution!"); }}Copy the code
  • The execution result is as follows:

5. Thread enforcement (Join)

  • Join joins the thread. After the execution of this thread is complete, the execution of other threads will be blocked
  • It’s like jumping the queue.
  • Code examples:
/** * thread execution -- queue jumping */
public class TestThreadJoin implements Runnable {

    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(new TestThreadJoin());
        for (int i = 0; i < 400; i++) {
            System.out.println("Main thread is queuing!!" + i);
            if (i == 100) { thread.start(); thread.join(); }}}@Override
    public void run (a) {
        for (int i = 0; i < 100; i++) {
            System.out.println("VIP thread jumping the queue!!"+ i); }}}Copy the code
  • The execution result is as follows: wait for the queue jumping thread to finish executing, then continue to execute the main thread!


I see no ending, but I will search high and low

If you think I blogger writes good! Writing is not easy, please like, follow, comment to encourage the blogger ~hahah