Communication Thread - Java multi-threaded (5)

Communication thread

Introduction:
Use two threads to print 1-100. Thread 1, Thread 2 alternate print
at this time if only synchronization lock Although you can interact with print, but can not complete the alternate print

package JavaThread;
class Window implements Runnable{
    private int num=1;
   public void run(){
       while(true){
           synchronized(this){
               if(num<=100) {
                   try {
                       Thread.sleep(10);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   System.out.println(Thread.currentThread().getName() + "打印:" + num);
                   num++;
               }else{
                   break;
               }
           }
       }
   }
}
public class Test {
    public static void main(String[] args) {
        Window w=new Window();
        Thread t1=new Thread(w);
        Thread t2=new Thread(w);

        t1.setName("线程一");
        t2.setName("线程二");

        t1.start();
        t2.start();
    }
}

If you want to print then they would use to complete the alternate communication between threads to complete, when a thread after printing the cpu it is imperative to thread two and myself is blocked, thread two is the same reason

The method requires the use of:
the wait () and notify () and notifyAll (

  1. wait (): make the current thread hangs and give up CPU, synchronization of resources and wait for the other thread can access and modify shared resources, and the current thread waiting another thread invokes the notify () or notifyAll () method awaken, wake wait All of the monitors to regain
    the right to continue.
  2. notify (): the highest priority thread wakeup queuing to wait for the end of a synchronized resource
  3. notifyAll (): wake resources are lining up all the threads waiting for the end of the waiting .

note:

  • These three methods can be used only in the synchronized method or synchronized block of code, otherwise it will be reported java.lang.IllegalMonitorStateException exception.
  • Because these three methods must have a lock object to call, but any object can be used as synchronization lock synchronized, so these three methods can only be declared in the Object class.

wait () method

  • Call methods in the current thread: object name .wait ()
  • The current thread into the wait (an object) until another thread of the object to issue the Notify
    (or notifyAll) so far.
  • A necessary condition for calling the method: the current thread must have the right to monitor the object (lock)
  • After calling this method, the current thread will release the object right to monitor, and then enter the wait
  • After the current thread is notify, to regain the right to monitor, and then continue to execute code from the breakpoint.

notify()/notifyAll()

  • Call methods in the current thread: object name .notify ()
  • Function: Wake wait for the object of a monitoring authority / all threads.
  • A necessary condition for calling the method: the current thread must have the right to monitor the object (lock)
class Number implements Runnable{
    private int number=1;
    public void run(){
        while(true){
            synchronized(this) {
                notify();
                if (number <= 100) {
                    try {
                        Thread.sleep(10);//进入阻塞不释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ": " + number);
                    number++;
                    try {
                        //使得调用 wait()方法的线程进入阻塞状态会释放锁
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}
public class Thread01 {
    public static void main(String[] args) {
        Number nu=new Number();
        Thread t1=new Thread(nu);
        Thread t2=new Thread(nu);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}

When entering the synchronized block line Chengyi Gang will wake up two threads, so that two threads waiting outside, when the thread enters a printing num wait () state, the thread releases the lock in the synchronization code will be two blocks, step empathy.

Similarities and differences sleep () and wait () of

  1. The same point: Once the method is performed, so that the current thread may enter the blocking state.
  2. Different points: 1) the method declaration two different positions: the Thread class declaration sleep (), Object class declaration wait ()
  3. Call different requirements: sleep () can be called at any desired scene. wait () must be used, or a block synchronization code synchronization method
  4. Synchronization monitor whether the release: If both methods are used in the synchronization code blocks or synchronization methods, sleep () will not release the lock, wait () releases the lock.
Published 45 original articles · won praise 43 · views 7069

Guess you like

Origin blog.csdn.net/qq_42193790/article/details/104440990