Two ways to implement Java multithreading (from official sources)

Keywords: Java Google

Source overview

I'm just preparing for the interview. So it seems like there's a way to implement Java County Town, so Baidu (though rumored to be dead) and Google. And then the result...
[Image-10f8bf-1569247170008]

This pit is unbearable! The answer can't be more powerful.
If there is such a problem in the written examination or interview, it is estimated that how many interviews will die, and we still don't know what the root cause is!!! That's pretty scary.
So find the official java tutorials to find the results:

This means that there are only two ways to implement threads

Realization way

The first implementation of Runnalble interface

Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}

The second inheritance of the Thread class

Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:


public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}

Tips

Notice that both examples invoke Thread.start in order to start the new thread.

  1. Start the start method call with the thread object, as in the two sample programs above.
  2. The implementation code is written in the run method, or called directly or indirectly by the run method.

Doubt

  1. Thread method is also implemented by implementing Runnable interface. Can it be reduced to one?

Official two kinds, as for the programmer himself humming and humming all understand ha!!!

  1. What about FutureTask + Callable interface, Executors.new.*ThreadPool and internal class implementation?

Answer: These are both ways to expand one of the above two. The internal class is that way. The others are as follows:

  • Thread Implementation with Return Value (FutureTask + Implementing Callable Interface)

    FutureTask implements the Runnable interface, which includes the call method to call the interface Callable interface. So it is possible to implement the thread by implementing Callable, which is the first thread implementation method. The FutureTask code is as follows:
 public class FutureTask<V> implements RunnableFuture<V> {
  // Rewriting the run method is just an internal implementation
  public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable; // Use Callable
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();  // Running call method
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);  // Set the return value
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
}

  • Thread pool-based approach (Executors.new.*ThreadPool)

Executors.new.*ThreadPool is implemented by creating a new ThreadPool Executor tired, and is represented as a queue of work tasks, so this is also the first thread implementation. The Executors code is as follows:

  public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
      public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {// Implementation of Runnable Interface by Workthread Queue
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

summary

There are still pits on the internet, and they fell in accidentally. It's easy to know what's wrong with this obvious thread implementation problem, and it's not too difficult to find the correct solution. But think about the problems we often encounter, which are "endless emergence"? The solution that searches on the net is so "a hundred flowers blossom" (whether you are right or wrong). So don't pay attention to every problem, it's not enough at all.

  • Learning materials, try to learn from official documents, classical textbooks;
  • Problem solving, multi-party search, various deliberations, inevitably a variety of source code search;

The problem of simple thread implementation that has troubled Benshuai for many years

Posted by juschillinnow on Mon, 23 Sep 2019 07:12:22 -0700