java multithreading (3) - thread-safety issues and genlock

Classic ticket issue
window while 1,2,3 sell 100 tickets
here complete with the interface form

package JavaThread;
class Window implements Runnable{
    int ticket=100;
    public void run(){
        while(true) {
            if (ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖出第:" + ticket + "张票");
                ticket--;
            } 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);
        Thread t3=new Thread(w);

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

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

Here Insert Picture Description
The reason for re-vote or wrong ticket: When a thread enters a judgment at this time
of the vote may be the first one and then determine just finished will appear blocking (sleep), then went cpu thread of execution threads while the second is to determine two first tickets, thread two finished so that ticket minus 1, ticket 0, which is the cpu reassigned to a thread, a thread output 0.
Appears wrong ticket
and produce heavy voting because when the thread is a complete implementation of the output statement, the thread has not suddenly switch leads to ticket minus 1, other threads and took the same data into judgment output again resulting in heavy ticket.

Atomicity operation concept:
Here Insert Picture Description

To ensure the security thread running it provides a solution to synchronization mechanism

Sync block:

synchronized (object) {
// the code to be synchronized;
}

Principle: even in the event of blocking, when the code is contained in the synchronized block other threads then execute this code can not be operated until the thread is finished.
For example: If the toilet life, you at your convenience a separate toilet, others anxious even then you have to wait to complete.

Synchronization monitor: commonly known lock, the synchronization code block needs to act as a lock object as a parameter, a class of any object, can act as locks.
Requirements: multiple threads must share the same lock.
For example: the equivalent of that lock on the toilet door, you do not lock up talent to enter.

class saleTh implements Runnable{
    private  int ticket=100;
    //Object obj=new Object();
    public void run(){
        while(true){
            synchronized(this){//此时的this唯一的window对象(第二种方法——>)synchronized(obj){
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":卖票" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
public class safeThread {
    public static void main(String[] args) {
        saleTh s=new saleTh();
        Thread t1=new Thread(s);
        Thread t2=new Thread(s);
        Thread t3=new Thread(s);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

This is a re-vote would not have the wrong ticket

Description
Code 1. The operation of the shared data, the code that is to be synchronized. -> can not contain code for more, and can not contain less code.
2. Shared data: Variable multiple threads co-operation. For example: ticket is the sharing of data.

Fast synchronization code applied to the method of the Thread inherited

class window2 extends Thread{
    private static int ticket=100;
    private static Object obj=new Object();
    public void run(){
        while(true){
            synchronized(window2.class){//window2.class只会加载一次类也是对象synchronized(obj) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ":票号为" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}

public class ThreadPratice2 {
    public static void main(String[] args) {
        window2 t1=new window2();
        window2 t2=new window2();
        window2 t3=new window2();
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

Here the data set to a static because the inherited method to create three objects to make them share the 100 votes it needs to static methods to achieve natural runnable interface to share data, which also can use the class to act as a lock, because classes are objects

Synchronization method

Implement runnable interfaces

class sale implements Runnable{
    private  int ticket=100;
    public void run(){
        while(true){
            show();
        }
    }
    private  synchronized void show(){//同步监视器 this
        if(ticket>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":卖票"+ticket);
            ticket--;
        }
    }
}
public class Thread01 {
    public static void main(String[] args) {
        sale s=new sale();
        Thread t1=new Thread(s);
        Thread t2=new Thread(s);
        Thread t3=new Thread(s);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}

Inheritance Thread

class window extends Thread{
    private static int ticket=100;
    public void run(){
        while(true){
            show();
        }
    }
    private static  synchronized void show(){//同步监视器 当前的类window.class
    //private synchronized void  show(){这种方法是错的 同步监视器不为一个 t1 t2 t3
        if(ticket>0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":票号为" + ticket);
            ticket--;
        }
    }

}
public class Thread02 {
    public static void main(String[] args) {
        window t1=new window();
        window t2=new window();
        window t3=new window();
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

Synchronization method will automatically add the object lock

Supplementary :

Release the lock operation

  1. The current thread synchronization method, the synchronization code block execution ends.
  2. The current thread encounters a break in the synchronized block, synchronization method, return to terminate the code block,
    to continue carrying out the method.
  3. The current thread appeared untreated Error or Exception block synchronization, synchronization method, the guide
    induced abnormal end.
  4. The current thread of execution object thread synchronization code block, the synchronization method wait () method, the current line
    process pause, and release the lock.

It will not release the lock operation

  1. When the synchronization code synchronization method blocks or thread of execution, the program calls the Thread.sleep (),
    to Thread.yield () method to suspend execution of the current thread
  2. Thread synchronization code block, another thread invokes the thread a suspend () method of the thread is
    suspended, the thread does not release the lock (synchronization monitor).
     should avoid using suspend () and resume () to control thread
Published 45 original articles · won praise 43 · views 7073

Guess you like

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