The face of Java multi-threaded, or a cool give yourself?

Java multi-threading, the name sounds should be quite afraid of how many people had been in this pit. That pits it really is each a carrot a pit, a basket of carrots Montreal pit. To give you an example of an image, which is like you build a house, the house quickly capped, feeling nothing wrong, then your opening line cap when the wall collapsed. It is this feeling, very hard to accept. If you can not appreciate this feeling, just give you one just like you go to a hotel and even personal (as for doing, we can not ask), and then you feel no problem, just when you try it, just you get ready for battle, I felt like a volcano about to erupt when, suddenly, a pot of cold water to come and tell you, brother, you can not. This is what it feels like. This is the feeling you use threads.

Technology already own vegetables, Java is not much understanding. Just encountered a very distressing thing. What happened was this:

Cases playback

Due to the need, I want to get a return value Runnable inside. for example:

class MyRunnable implements Runnable{
    int id = 0 ;
    @Override
    public void run() {
        id = 1 ;
    }
}

Uncertainty about the accuracy of this case. Now I go to instantiate the MyRunnable, I'm going to get it inside id, but then, how do you get to it? Get out, you get there may be zero, people have not assigned it, there has returnnot, very unhappy people.

solve

You can not get this after being reassigned in a real environment idvalues. That question is, I have to get, then I can wait to pick up the implementation of End run, how do I know that it Shashi Hou implementation of End? As long as the time is not long, or you can wait. And, um, Runnable particularly nasty. We look at this Runnable, she is actually a function interface. From JDK1.0 to follow, and this is the veteran class. No wonder so difficult to use. And then, we know, Thread class is an implementation of the Runnable. So we write thread, usually with a Thread, or Runnable.

I struggled for a long time on the Internet, and see an interface very similar to Runnable (when previously learned Java, there are see this, but for a long time, forget), called Callable. We look at the source code:

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Did not see, he can return this value, that is, we just need to implement this interface, he can be returned to our calculations, is not it. Now the question again. He recognized our thread Runnable, we supposed to? Not afraid, we have a thing: FutureTask<V>the source code, let's look at a diagram:
Here Insert Picture Description

Do not look at anything else, there's a look at two constructors:

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

Look at the interface he realized:

implements RunnableFuture<V>

public interface RunnableFuture<V> extends Runnable, Future<V> 

Now, this is equivalent to a FutureTask the Runnable. It can be added to our Thread inside. We look at this FutureTask inside the run method:

    public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } 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);
        }
    }

You can see, the final result is to set a bit. The result is the call returns the result, this is the case, we are not equivalent and other threads executing the got results yet. This time still can wait.

Proceed as follows:

  • Callable achieve a class, inside rewriting method call;
  • Examples of the implementation class FutureTask added to go inside;
  • Examples of the FutureTask added to the thread Thread inside.
  • Get the value. Use future.get (), if the thread is not executed, this will be blocked live.

to sum up

Multi-threaded use is actually very complex, which can be written in a book, we have to do is to each their own problems recorded, and then share it. This is the significance of the blog.

Published 100 original articles · won praise 32 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_33356083/article/details/105276186