java multithreading: 3, sleep (), wait (), notify (), the difference between the notifyAll (), run (), start ()?

1 except sleep (), wait () of

sleep (): Specifies the thread sleep, go to sleep. We will take the initiative to let the CPU, after a specified period of time, enter the ready state, waiting for the CPU to allocate this thread to continue. In this process, it will not release the lock. (Holding objects to sleep, do not release the lock)

wait (): Interrupt threads running, so that the thread waits temporarily give up the right to use the CPU, and allow other threads to use this synchronization method. It will release the lock. Only when the other thread calls the notify (), notifyAll () method, the thread will wait has officially joined the competition to acquire a lock, but not immediately acquire the lock to wait before they can get the lock after the lock is released.

2, the difference notify (), notifyAll () of

To understand notify (), notifyAll () of the difference, we must first understand the lock pool and wait pool.

Lock pool: only get a lock object, synchronized thread to execute the code objects, lock objects that only one thread can get, other threads can only wait for the lock pool

Wait pool: After a hypothesis A thread calls wait an object () method, thread A releases the lock of the object, into the pool to wait for the object, the thread will not wait for the pool to compete lock of the object .

notify (): a random thread wake object waiting in the pool, the pool into the lock.

notifyAll (): wake up all threads waiting for object pool, the pool into the lock.

So wake up the thread, the thread is waiting for the pool to lock the pool, after notifyAll call, all threads will be moved by the pool waiting for the lock pool, the lock and then participate in the competition, competing successfully proceed, if unsuccessful, to stay in after the lock pool waiting for the lock to be released to compete again. The wake will notify a thread.

So why wait (), notify () will cause a deadlock it?
I do not know, know to supplement.

3, the difference run (), start () of

In general, the systems start calling thread class () method to start a thread, the thread is in the ready state at this time. Only when a thread is CPU, it will automatically call their own run () method into operation, after the end of the run () method, the thread into the death state.

If direct calling thread's run () method, it will be treated as a normal function call, and can not open a new thread. Directly call run () method is synchronous, it can not achieve the purpose of multiple threads, and start () method can be called asynchronously run () method, to achieve multi-threading.

Published 57 original articles · won praise 13 · views 1097

Guess you like

Origin blog.csdn.net/weixin_42924812/article/details/105209868