Java multi-threading, thread safety examples

Create a thread

Java uses java.lang.Thread class represents a thread, all the thread object must be an instance of the Thread class or subclass.

Thread class

public class MyThread extends Thread{
    public MyThread(String name) {
        //调用父类的String参数的构造方法,指定线程的名称
        super(name);
    }

    /**
     * 重写run方法,完成该线程执行的逻辑
     */
    @Override
    public void run() {
        try {
            sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 0; i < 100; i++) {
            System.out.println(getName() + i);
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        //创建自定义线程对象
        MyThread mt1 = new MyThread("a");
        MyThread mt2 = new MyThread("b");
        MyThread mt3 = new MyThread("c");
        //开启新线程
        mt1.start();
        mt2.start();
        mt3.start();
        //主线程中的for循环
        for (int i = 0; i < 20; i++) { 
       		System.out.println("主线程:"+i); 
        }
    }
}

Main program starts running time, java virtual machine to start a process, the main thread main () call when they were created in the main. With the start method is called object mt, the other three also launched a new thread, so that the entire application to run in multi-threaded.

Runnable Interface

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + i);
        }
    }
}
public class RunableTest {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();

        new Thread(mr, "a").start();
        new Thread(mr, "b").start();
        new Thread(mr, "c").start();
    }
}

By implementing Runnable interface, characterized in that with such a multi-threaded type. run () method is a multi-threaded execution of the target program. All multithreaded code in the run method inside. Thread class is actually a class that implements the Runnable interface.

At startup multithreading, we need to construct objects through the Thread class constructor Thread (Runnable target), and then call the object's start Thread () method to run multithreaded code.

Virtually all multi-threaded code is by start () method of the Thread run to run. Therefore, whether to inherit the Thread class or implement Runnable interface to achieve multi-threaded, ultimately controlled by API thread Thread object, familiar with the Thread class API is the foundation for multi-threaded programming.

Implement Runnable than the Thread class inherits the advantages

  • Program code for multiple threads of the same to share the same resources
  • To avoid the limitations of single inheritance in java
  • Increase the robustness of the program, decoupling operation, code can be shared by multiple threads, and thread codes independently
  • Thread pool can only achieve Runable or Callable classes into a thread, not directly into the inheritance Thread class.

In java, every time the program starts to run at least two threads. One is the main thread, a garbage collection thread. Because every time a class using the java command, in fact, will start a JVM, each JVM in fact, it is to start a process in the operating system.

Thread Safety

If there are multiple threads running at the same time, and these threads may run this code at the same time. The results of each program and run single-threaded operating results are the same, and also the values of other variables and expectations are the same, that is thread-safe.
The following simulation demonstrates the ticket thread safe:

public class Ticket implements Runnable {
    private int ticket = 100;
    @Override
    public void run() {
        while (true) {
            if (ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String name = Thread.currentThread().getName();
                System.out.println(name + "正在卖:" + ticket);
                ticket--;
            }
        }
    }
}
public class Test1 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        Thread t1 = new Thread(ticket, "窗口1");
        Thread t2 = new Thread(ticket, "窗口2");
        Thread t3 = new Thread(ticket, "窗口3");

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

Partial results:
Here Insert Picture Description

Thread Synchronization

When we use multiple threads access the same resources, and the resources of multiple threads in a write operation, thread-safety issues are likely to arise.
In order to ensure that each thread can perform atomic operations normal, Java introduces a thread synchronization mechanism. There are three ways to complete the synchronization operation:

  • Sync block
  • Synchronization method
  • Lock mechanism

Sync block

synchronizedKeywords can be used in the process of a block, this block represents only the resources were mutually exclusive access.

synchronized(同步锁) {
	需要同步操作的代码
}

Synchronization lock is an abstract concept, lock object may be any type, such as new Object () can be.

public class Ticket implements Runnable {
    private int ticket = 100;

    Object obj = new Object();

    @Override
    public void run() {
        while (true) {
           synchronized (obj) {
               if (ticket > 0) {
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   String name = Thread.currentThread().getName();
                   System.out.println(name + "正在卖:" + ticket);
                   ticket--;
               }
           }
        }
    }
}

Synchronization method

Use synchronized modified method is called synchronization methods to ensure a thread in the implementation process, the other thread blocks waiting for.

public synchronized void method() {
	可能产生线程安全问题的代码
}
public class Ticket implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            payTicket();
        }
    }

    public synchronized void payTicket() {
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String name = Thread.currentThread().getName();
            System.out.println(name + "正在卖:" + ticket);
            ticket--;
        }
    }
}

Synchronization method payTicket () may be set to a static, non-static method for synchronization lock is the this, static methods, using the current bytecode object class methods where (class name .class).

Lock Lock

Lock Lock, also known as genlock

  • public void lock (): plus genlock
  • public void unlock (): release the synchronization lock
public class Ticket implements Runnable {
    private int ticket = 100;

    Lock l = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
           l.lock();
            if (ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    String name = Thread.currentThread().getName();
                    System.out.println(name + "正在卖:" + ticket);
                    ticket--;
                    l.unlock();
                }
            }
        }
    }
}
Published 243 original articles · 87 won praise · views 70000 +

Guess you like

Origin blog.csdn.net/IT_10/article/details/104070077