About Thread.sleep () method

sleep () method does not release the lock, but the release cpu;
if there are multiple threads operating in a lock resource, if a thread owns the lock, but in the implementation of the method of implementation of the sleep () method. Only other threads in the thread wakes up and executing the method, after releasing the lock, and the thread can lock resources to compete again.
A ticket Example:
class MyThread2 the implements the Runnable {

private int TICKET = 5;

@Override
public void run() {
    while (true) {
        synchronized (this) {
            if (this.TICKET > 0) {
            //得到当前线程名字
            System.out.print(Thread.currentThread().getName());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println( "卖票:票数剩余:" + (--TICKET));
            } else {
                System.out.println("票已经卖完");
                break;
            }
        }
    }
}

}
The results:
conductor A ticket: remaining votes: 4
conductor A ticket: remaining ballots: 3
conductor ticket C: The remaining ballots: 2
conductor C ticket: remaining ballots: a
conductor C ticket: remaining votes: 0
votes It has been sold out
tickets have been sold out
tickets have been sold out
after possession when thread a lock, a conductor found the hands of a vote (votes> 0), even though it slept 100ms, it is always the successful ticket sold. Instead it during sleep, snatched away by another thread locks, tickets did not sell. Only after executing the if statement, out of synchronized () {} After the method body, will lock resources with other resources to snatch again.
Explain here why use while (true) {} structure wrapped up, because each thread Thread.start () will be executed once run () method. Once out, he could not come up, the result is that each thread can only sell a ticket.
sleep () method will release the cup resources, just holding the lock, instead of cpu time slice. Other threads can perform other resources in addition to the possession of the lock.

Published 14 original articles · won praise 0 · Views 334

Guess you like

Origin blog.csdn.net/qq_38205881/article/details/103548904