java learning as much as a thread articles

(1) multi-threading: An application are multiple execution paths

        Process: the application being executed. The program is running, the system resource allocation and called independent units. Each process has its own memory space and system resources.

        Thread: executing means for executing the process path (in a single sequential process flow of control is an execution path)

        Single-threaded: An application has only one execution path

        Multithreading: An application are multiple execution paths

 

        Meaning multi-process?

            Improve CPU utilization

        Meaning multiple threads?

            Increased usage of applications

 

        Parallel and Concurrent:

            Logically it is parallel simultaneously, means to run simultaneously within a certain time a plurality of programs.

            Concurrency is simultaneously physically means a plurality of programs to run simultaneously at a certain time point.

 

    Operating principle (2) Java program and starting the JVM is multithreaded do?

        A: Start by the java command JVM, JVM start the equivalent of starting a process. Then there is the process creates a main thread to call the main method.

        B: JVM startup is multi-threaded, because the garbage collection thread also first started, it will easily appear out of memory. Now garbage collection thread together in front of the main thread,

           Minimum start two threads, so, the JVM startup in fact be multi-threaded.

    (3) multi-threaded implementations (master)

        A: Thread class inheritance

           1. Step:

          A: MyThread custom classes inherit the Thread class.

          B: MyThread class which override run ()

              Why run () method do?

                All code is not in the class need to be a thread of execution. And this time, in order to be able to distinguish what a thread of execution of code, java provides a Thread class  

                 run () to those containing a thread of execution code

          C: create objects MyThread my1 = new MyThread ();

          D: starting a thread my1.start ();

          

          note:

              1. The  difference between the run () and start () are?

                  run (): the code packages are simply a thread of execution, a direct call is a common method

                  start (): First start the thread, and then call the jvm to run this thread () method.

               2.my1.start (); my1.start (); IllegalThreadStateException: Illegal thread abnormal state

                    Because this is the equivalent of my thread is called twice. Instead of two thread starts.

 2. Get the name of the method / set the thread:

     public final String getName (): Get the name of the thread.

     Set the name of the thread: public final void setName (String name)

     public static Thread currentThread (): Returns the currently executing thread object

     Thread.currentThread().getName()

          

        B: implement Runnable

             step:

          A: custom class MyRunnable implement Runnable

          B: override run () method

          C: Create a class of objects MyRunnable

          D: Create Thread class objects, and the object C as the configuration parameter transfer step

    (4) thread scheduling and priority issues

        A: thread scheduling

            a: time-sharing scheduling

            b: preemptive scheduling (Java is used in the scheduling mode)

        B: get and set the thread priority

               public final int getPriority (): Returns the thread object's priority

               public final void setPriority (int newPriority): Changing thread priority.

                 Thread default priority is 5.

       Range of thread priority is: 1-10.

       High thread priority only indicates a high probability thread gets CPU time slice, but more to the number of times, or when running multiple times in order to see better results.

 

            IllegalArgumentException: illegal argument exception. Thrown to indicate that passed an illegal or incorrect parameter to the method.

    Control (5) threads (common method)

        A: sleeping thread

               public static void sleep(long millis)

        B: adding thread

                public final void join (): Waits for this thread.

        C: comity thread

               public static void yield (): pause the currently executing thread object, and perform other threads. Let execute multiple threads of a more harmonious, but can not be relied on to ensure that a person once.

        D: background thread

               public final void setDaemon (boolean on): this thread is marked as a daemon thread or a user thread.

               When running thread is a daemon thread, Java virtual machine exit. This method must be called before starting the thread.

        E: terminate the thread (master)

               public final void stop (): thread to stop, out of date, but can also be used.

               public void interrupt (): interrupt thread. The state of the thread to terminate, and throw an InterruptedException.

 

    (6) the life cycle of the thread

        A: New

        B: Ready

        C: Run

        D: blocked

        E: Death

     The thread state transition diagram and common implementation:

   

Implement (7) cinema ticket program

        A: Thread class inheritance


public class SellTicket extends Thread {

    // 定义100张票

    // private int tickets = 100;

    // 为了让多个线程对象共享这100张票,我们其实应该用静态修饰

    private static int tickets = 100;



    @Override

    public void run() {

        // 定义100张票

        // 每个线程进来都会走这里,这样的话,每个线程对象相当于买的是自己的那100张票,这不合理,所以应该定义到外面

        // int tickets = 100;



        // 是为了模拟一直有票

        while (true) {

            if (tickets > 0) {

                System.out.println(getName() + "正在出售第" + (tickets--) + "张票");

            }

        }

    }

}



/*

 * 某电影院目前正在上映贺岁大片(红高粱,少林寺传奇藏经阁),共有100张票,而它有3个售票窗口售票,请设计一个程序模拟该电影院售票。

 * 继承Thread类来实现。

 */

public class SellTicketDemo {

    public static void main(String[] args) {

        // 创建三个线程对象

        SellTicket st1 = new SellTicket();

        SellTicket st2 = new SellTicket();

        SellTicket st3 = new SellTicket();



        // 给线程对象起名字

        st1.setName("窗口1");

        st2.setName("窗口2");

        st3.setName("窗口3");



        // 启动线程

        st1.start();

        st2.start();

        st3.start();

    }

}

        B: implement Runnable


public class SellTicket implements Runnable {

    // 定义100张票

    private int tickets = 100;



    @Override

    public void run() {

        while (true) {

            if (tickets > 0) {

                System.out.println(Thread.currentThread().getName() + "正在出售第"

                        + (tickets--) + "张票");

            }

        }

    }

}



/*

 * 实现Runnable接口的方式实现

 */

public class SellTicketDemo {

    public static void main(String[] args) {

        // 创建资源对象

        SellTicket st = new SellTicket();



        // 创建三个线程对象

        Thread t1 = new Thread(st, "窗口1");

        Thread t2 = new Thread(st, "窗口2");

        Thread t3 = new Thread(st, "窗口3");



        // 启动线程

        t1.start();

        t2.start();

        t3.start();

    }

}

    (8) cinema ticketing program problems

        A: In order to better meet the real scene, joined the sleep of 100 milliseconds.

        B: ticket issue

            a: the same ticket several times

            b: negative votes


public class SellTicket implements Runnable {

    // 定义100张票

    private int tickets = 100;



    @Override

    public void run() {

        while (true) {

            // t1,t2,t3三个线程

            // 这一次的tickets = 1;

            if (tickets > 0) {

                // 为了模拟更真实的场景,我们稍作休息

                try {

                    Thread.sleep(100); //t1进来了并休息,t2进来了并休息,t3进来了并休息,

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }



                System.out.println(Thread.currentThread().getName() + "正在出售第"

                        + (tickets--) + "张票");

                //窗口1正在出售第1张票,tickets=0

                //窗口2正在出售第0张票,tickets=-1

                //窗口3正在出售第-1张票,tickets=-2

            }

        }

    }

}



/*

 * 实现Runnable接口的方式实现

 *

 * 通过加入延迟后,就产生了连个问题:

 * A:相同的票卖了多次

 *         CPU的一次操作必须是原子性的

 * B:出现了负数票

 *         随机性和延迟导致的

 */

public class SellTicketDemo {

    public static void main(String[] args) {

        // 创建资源对象

        SellTicket st = new SellTicket();



        // 创建三个线程对象

        Thread t1 = new Thread(st, "窗口1");

        Thread t2 = new Thread(st, "窗口2");

        Thread t3 = new Thread(st, "窗口3");



        // 启动线程

        t1.start();

        t2.start();

        t3.start();

    }

}

    (9) The reason multi-threaded security issues (we later determine is whether there is a program based on thread safety issues)

        A: Whether multithreaded environment

        B: Is there a shared data

        C: Are there multiple operating statement data sharing

    (10) synchronous solve thread safety issues

          The code multiple statements to the operation of shared data package as a whole, so that when a thread of execution, others can not be performed.

        A: synchronization code blocks

            synchronized (object) {

                Synchronization code is required;

            }

 

            Here's lock object can be any object.

            Time to pay attention to solve the problem: multiple threads must be the same lock.

 

        B: synchronization method

            The synchronization method is applied on.

            Here is this lock object

 

        C: static synchronized method

            The synchronization method is applied on.

            Here the lock object is a file object bytecode current class (reflection)

 

       Synchronization of benefits

            It appears synchronization solution to the security problems of multithreading.

       Synchronization of malpractice

            1. When the thread is quite a long time, because each thread synchronization lock on to judge, this is a very resource-intensive, would effectively reduce the efficiency of the program. (low efficiency)

            2. prone to deadlock


public class SellTicket implements Runnable {



    // 定义100张票

    private int tickets = 100;



    // 定义同一把锁

    private Object obj = new Object();



    @Override

    public void run() {

        while (true) {

            // t1,t2,t3都能走到这里

            // 假设t1抢到CPU的执行权,t1就要进来

            // 假设t2抢到CPU的执行权,t2就要进来,发现门是关着的,进不去。所以就等着。

            // 门(开,关)

            synchronized (obj) { // 发现这里的代码将来是会被锁上的,所以t1进来后,就锁了。(关)

                if (tickets > 0) {

                    try {

                        Thread.sleep(100); // t1就睡眠了

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    System.out.println(Thread.currentThread().getName()

                            + "正在出售第" + (tickets--) + "张票 ");

                    //窗口1正在出售第100张票

                }

            } //t1就出来可,然后就开门。(开)

        }

    }

}

public class SellTicketDemo {

    public static void main(String[] args) {

        // 创建资源对象

        SellTicket st = new SellTicket();



        // 创建三个线程对象

        Thread t1 = new Thread(st, "窗口1");

        Thread t2 = new Thread(st, "窗口2");

        Thread t3 = new Thread(st, "窗口3");



        // 启动线程

        t1.start();

        t2.start();

        t3.start();

    }

}

 

    (11) Recalling the previous thread-safe class

        A:StringBuffer

        B:Vector

        C:Hashtable

        D: how to put a thread-safe collection classes into a thread-safe collection classes

            Collections can be a method of tools.


        // 线程安全的类

        StringBuffer sb = new StringBuffer();

        Vector<String> v = new Vector<String>();

        Hashtable<String, String> h = new Hashtable<String, String>();



        // Vector是线程安全的时候才去考虑使用的,但是我还说过即使要安全,我也不用你

        // 那么到底用谁呢?

        // public static <T> List<T> synchronizedList(List<T> list)

        List<String> list1 = new ArrayList<String>();// 线程不安全

        List<String> list2 = Collections

                .synchronizedList(new ArrayList<String>()); // 线程安全

 

Published 114 original articles · won praise 52 · views 20000 +

Guess you like

Origin blog.csdn.net/Smile_Sunny521/article/details/89704158