Java multi-threading implementation and introduction JUC

Implementation of multi-threaded (inherited his father's classes and implement interfaces) three

  1. Inherit the parent class Thread, override the run () method
    [implement]
class MyThreadEx extends Thread{

        private String title;
        MyThreadEx(String title){
            this.title = title;
        }

        @Override
        public void run() {
            for (int i = 0;i < 10;i++){
                System.out.println(currentThread().getName()+"--"+title+":"+i);
            }
        }
    }

【transfer】

MyThreadEx thread = new MyThreadEx("A");
thread.start();
  1. Implement the interface (Runnable) implement the interface method run ()
    [realize]
class MyThread implements Runnable{

        private int i = 0;

        @Override
        public void run() {
           for (;i < 10;i++)

            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }

【transfer】

     MyThread runthread = new MyThread();
        new Thread(runthread,"A").start();
  1. Implement the interface (a Callable) implement interface method call () (JUC after 1.5, return value)
    a Callable Principle:

【achieve】

class MyCallThread implements Callable{

        private int i = 0;

        @Override
        public Object call() throws Exception {

            for (; i < 10; i++){
                System.out.println(Thread.currentThread() + "-callable:"+ i);
            }
            return "callable";
        }
    }

【transfer】

 FutureTask<String> task = new FutureTask<>(new MyCallThread());

        new Thread(task).start();

        System.out.println(task.get());

After java1.5 java.util.concurrent (concurrent: concurrent)

atomic: atom, AtomicInteger: atomic reference

1.volatile lightweight synchronization mechanism provided by the java virtual machine
properties:
(1) ensure the visibility
(2) does not guarantee atomicity
(3) prohibition instruction rearrangement

  • Simple interest failure mode in multiple threads (two ways to achieve Singleton pattern: the lazy and hungry man), with DCL (Double Check Lock)
public class Singleton{
  private static volatitle Singleton instance = null; //volatitle轻量级线程同步机制
    private Singleton(){
    }
    public static Singleton getInstance(){ //方法加synchronized,效率低
        if(instance == null){
            synchronized(Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
    }
}

2.JMM: (java memory model) java memory model, abstractions, not real

JMM synchronization requirements:
Before (1) thread unlock value must be shared refresh back to main memory
(2) before locking thread, must read the latest value of the main memory to their working memory
(3) is identical to lock unlock lock

Guess you like

Origin www.cnblogs.com/monkay/p/11376623.html