Common methods of operation multi-threaded (attached cattle off exercises)

1. Naming and thread made
if not set thread name, the thread is automatically assigned a name
Note: If the thread object directly call run () method, run () method can not be directly obtained in the current execution thread by getName () method name, but need to use Thread.currentThread () method to get the current thread, and then call the thread object's getName () method to get the name of the thread.
Code:

public class ThreadMethod extends Thread  {
    @Override
    public void run() {
        //this:  ThreadMethod类的对象, getName()获取当前线程的名称
        System.out.println(this.getName() + " thread(extends)");
    }
}
public static void main(String[] args) {
        Thread thread1 = new ThreadMethod();
        thread1.setName("打印输出线程");
        thread1.start();
        for (int i = 0; i < 10; i++) {
            Runnable runnable1 = new RunnableMethod();
            Thread thread2 = new Thread(runnable1, "线程-" + i);
            thread2.setName("业务线程-" + i);
            thread2.start();
            //主程序(程序入口)线程main
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName());
        }
    }

The method itself is a main thread, all threads are created and started by the main thread
whenever using the java command to explain procedures, have expressed launched a new JVM process. The main method is just a thread on this process only
thread death:
thread will end in three ways, after the state ended in death
(1) run () or call () method execution is completed, the normal end of the thread
(2) Thread throws an uncaught Exception Error or
the method easily lead to deadlock - (3) direct call to stop (the thread) method to end the thread
sleep () method: 2. thread sleep
after the thread to sleep until the expected time then resume execution (and to a ready state)
SLEEP () method has two overloaded forms:
(1) static void SLEEP (Long millis): the currently executing thread to pause millis milliseconds, and enters the blocked state, the method by system affect the accuracy and precision of the timer and thread scheduler.
(2) static void sleep (long millis, int nanos): the currently executing thread to suspend millis milliseconds plus nanos nanoseconds, and enters the blocking state, the precision and accuracy method by the system timer and the thread scheduler influences.

For single-core CPU: the true sense of the serial execution
for multi-core CPU: parallel on the same time the true meaning of the Executive
Thread.sleep:
(1) to suspend the thread into the blocked state
(2) to produce the CPU
(3) does not release the occupied the resource lock
(4) sleep time to return to the ready state
code implementation:

public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("Start: " + LocalDateTime.now());
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("End: " + LocalDateTime.now());
        }, "Thread-Sleep").start();
    }

3. Thread concession: yield () method
(1) to suspend the thread into the ready state
(2) to hand over the CPU, but not sure the specific time
(3) does not release the occupied resource lock
(4) have the same priority thread cross authority of the CPU
calls yield method does not make the thread into the blocked state, but to let the thread back to the ready state, it only needs to wait to reacquire CPU execution time, and this is not the same methods and sleep.
sleep () method declaration throws an exception, it calls sleep () method either catch the exception, either explicitly declared Thrown; and yield () method is not declared any exception thrown
specific code to achieve:

public static void main3(String[] args) {
        Runnable runnable = () -> {
            System.out.println("Start: " + LocalDateTime.now());
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread.yield();
            }
            System.out.println("End: " + LocalDateTime.now());
        };
        //单核CPU
        new Thread(runnable, "Thread-Sleep-1").start();//sleep
        new Thread(runnable, "Thread-Sleep-2").start();
        new Thread(runnable, "Thread-Sleep-3").start();
    }

4.join () method
call in the thread A thread B in the join method, thread A suspended until the thread B executed, A thread before continuing execution.
join () method is usually called by programs that use threads to be a big problem into a number of small problems, small problems each is assigned a thread. When all the small problems are addressed, then call the main thread to further action.
Code:

public static void main(String[] args) {
        Thread thread = new Thread(new RunnableJoin(), "Thread-A");
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "main中的代码");

    }
 class RunnableJoin implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 执行开始时间 :" + LocalDateTime.now());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 大量代码");
            System.out.println(Thread.currentThread().getName() + " 执行结束时间 :" + LocalDateTime.now());

        }
        }

The thread to stop
three ways stop threads:
(1) setting flag, the thread may be normal exit.
(2) using the stop method to force the thread exits, but the method is less secure so have been abandoned.
(3) using a interrupt Thread class () can interrupt thread
code implementation:


    class RunnableStop implements Runnable {

        private boolean flag = true;

        @Override
        public void run() {
            int i = 0;
            while (flag) {
                try {
                 //这里阻塞之后,线程被调用了interrupte()方法,
                // 清除中断标志,就会抛出一个异常
// java.lang.InterruptedException
                    Thread.sleep(1000);//阻塞
                    //非阻塞
                    //此处有代码
                    boolean status = Thread.currentThread().isInterrupted();
                    if (status) {
                        System.out.println("非阻塞状态 " + status);
                        break;
                    }
                    i++;
                    System.out.println(Thread.currentThread().getName() + " 运行了 " + i + " 次");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //阻塞状态
                    boolean status = Thread.currentThread().isInterrupted();
                    //false 中断标志位清除
                    System.out.println("阻塞状态 " + status);
                    break;
                }
            }
            System.out.println(Thread.currentThread().getName() + " 终于停了");
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }
    }

 public static void main6(String[] args) {
        RunnableStop runnableStop = new RunnableStop();
        Thread thread = new Thread(runnableStop, "Thread-Stop-1");
//thread.stop();
        thread.interrupt();
        System.out.println(Thread.currentThread().getName() + "代码执行完了");
    }

interrupt () method simply changing the interrupt status only, it will not interrupt a running thread
interrupt () method does not perform interrupt operation immediately; specifically, this method will only give a thread set to true interrupt flag (interrupt flag just a Boolean variable), and after setting, the different subsequent operations depending on the current state of the thread. If, like the thread's current
state of the unblocked, then only the thread interrupt flag is modified it is true; if the current state of the thread is blocked, then after the break flag is set to true, there will be a case of one operation:
If it is blocked wait, sleep, and join three methods cause, then will re-thread interrupt flag is set to false, and throw an InterruptedException;
if at the time of interruption, the thread is unblocked, then modify the interrupt flag is true, and on this basis, once into the blocked state, blocking state according to the situation to be processed;
by triggering an interrupt, by the developer to decide how to handle thread business

Thread priority:
set the priority:
public void setPriority Final (int newPriority)
: get priority
public final int getPriority ()
to determine the content of the priority setting by a few constants Thread class

  1. Highest priority: public final static int MAX_PRIORITY = 10;
  2. Medium priority: public final static int NORM_PRIORITY = 5;
  3. Lowest priority: public final static int MIN_PRIORITY = 1 ;
    main thread (main) default priority is 5
    thread priority are inherited priority if the creating thread B thread A, the default priority inheritance thread A and B
    specific implementation code:
public static void main(String[] args) {
        Thread thread1 = new Thread(() -> System.out.println(Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority()), "Thread-1");
        thread1.setPriority(10);
        thread1.start();
        System.out.println(Thread.currentThread().getPriority());
        //main默认优先级是5
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority());
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority());
                    }
                }, "Thread-Parent-A-Name-is-B").start();
            }
        }, "Thread-Parent-main-Name-is-A").start();

    }
}

Cattle off topic:
the code is as follows:

import java.util.ArrayList;
import java.util.List;

public class NameList {
    private List names=new ArrayList();
    public synchronized void add(String name){
        names.add(name);
    }
    public synchronized void printAll(){
        for(int i=0;i<names.size();i++){
            System.out.println(names.get(i)+"");
        }
    }

    public static void main(String[] args) {
        final  NameList s1=new NameList();
        for(int i=0;i<2;i++){
            new Thread(){
                public  void run(){
                    s1.add("A");
                    s1.add("B");
                    s1.add("C");
                    s1.printAll();
                }
            }.start();
        }
    }
}

Analysis;
Thread 1 occupation add locks, after performing ABC release lock
thread 2 occupation add locks, after performing ABC release the lock
held by the thread 1 occupation printAll latch output, so the thread output 3-6 elements
thread after a completion of execution printAll method releases the lock , two execution thread lock printAll method and occupied, then add executing the shift, the second output 6 is equal to the number of characters
so execution results: ABCABCABC
may also be: AABBCCAABBCC, ABCAABCABC the like
since the addition order is uncertain characters, but to determine the first character must be added A.

Guess you like

Origin blog.csdn.net/weixin_42373873/article/details/91065604