java multithreaded II: Common Thread Operation

Article Source https://www.jianshu.com/p/33459d0c4a4b

Articles corresponding video source: https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

The main method of multithreading are defined in the Thread

Thread naming and made

  Multi-threaded operating status is uncertain, then the development process in order to be able to get some threads need to use the name of the thread can only rely on to operate.

  • Constructor: public Thread (Runnable target, String name);

  • Setting name: public final void setName (String name);

  • Have a name: public final String getName ();
    to get the thread object is not possible to rely on a just done this, because the state of the thread is not controllable, but one thing is clear, all the objects must execute threads run ( ) method, then this can be considered when acquiring the current thread, there is provided a method to get the current thread in the thread class:

  • Get the current thread: public static Thread currentThread ();
    Example: rename operation observe thread

class MyThread implements Runnable {//线程的主体类
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt = new MyThread();
        new Thread(mt, "线程A").start();//设置了线程名字
        new Thread(mt).start();//未设置线程名字
        new Thread(mt, "线程B").start();//设置了线程名字
    }
}

 When the developer is set thread name when you use the name of the set, and if the name is not set, it will automatically generate a unique name the, this automatic attribute named rely mainly on the static properties is completed, as defined in the Thread class which has as follows:

private static int threadInitNumber;
private static synchronized int nextThreadNum() {
    return threadInitNumber++;
}

Example: look at a program

 

class MyThread implements Runnable {//线程的主体类
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt = new MyThread();
        new Thread(mt, "线程对象").start();//设置了线程名字
        mt.run();//对象直接调用run()方法
    }
}

 

 By this time code can be found that when using the "mt.run ()" calling thread class object directly in the main method run () thread in the name of the object obtained by the method of "main", it can be drawn one conclusion: the main method is also a thread. So now the question is, are all threads in the process of dividing process so where? Whenever the java command when the execution of the program says that launched the process of a JVM, JVM can start several processes simultaneously on a single computer, so every JVM process will have their own threads.

In any development, the main thread can create several sub-thread, the child thread is created to some complex logic or time-consuming logic can be handed over to the sub-threading;
Example: sub-thread processing

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("1、执行操作任务一。");
        new Thread(()->{
            int temp=0;
            for(int i=0;i<Integer.MAX_VALUE;i++){
                temp+=i;
            }
        }).start();
        System.out.println("2、执行操作任务二。");
        System.out.println("n、执行操作任务N。");
    }
}

The main thread is responsible for handling the whole process, and the child thread is responsible for handling time-consuming operation.

 

Sleep thread

  If you want a thread may be suspended, then the process can be used to sleep, sleep method defined in the Thread class as follows:

  • public static void sleep​(long millis) throws InterruptedException

  • public static void sleep (long millis, int nanos) throws InterruptedException
      during sleep may generate an interrupt or exception "InterruptedException", belongs to a subclass Exception interrupt, so that the exception must be treated.
    Example: to observe the sleep process

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                }
                System.out.println(Thread.currentThread().getName() + "、i = " + i);
            }
        },"线程对象").start();
    }
}

The main features of sleep can automatically wake up the thread, to continue the subsequent processing. However, note that if there are multiple threads object, then there is also the order of dormancy.
Example: generating a plurality of threads sleep process objects

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Runnable run=() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "、i = " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int num = 0; num < 5; num++) {
            new Thread(run, "线程对象 - " + num).start();
        }
    }
}

In this case the object will have five threads, and five thread of execution method thereof is the same. At this point the program execution from the feeling seems to be carried out several threads together to sleep, and then carried out automatically wake up together, but in fact there is a difference. 

Thread interrupts

  Before the discovery of dormant provided there is a thread interrupt exception, in fact, prove dormant threads can be interrupted, and this must be done by interrupting other threads. In the Thread class which has provided this interrupt processing method performed:

  • Determining whether the thread is interrupted: public boolean isInterrupted ();

  • Interrupt thread execution: public void interrupt ();
    Example: observe the thread's interrupt handling operations

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(() -> {
            System.out.println("*** 累了,我该睡觉了");
            try {
                Thread.sleep(10000);//预计准备休眠10秒
                System.out.println("*** 睡足了,起床了");
            } catch (InterruptedException e) {
              System.out.println("被闹钟吵醒了");
            }
        });
        thread.start();//开始睡
        Thread.sleep(1000);
        if (thread.isInterrupted()==false) {//判断该线程是否已中断
            System.out.println("闹钟响了");
            thread.interrupt();//中断执行
        }
    }
}

 

All threads are being executed can be interrupted, the interrupted thread must be exception handling.

Thread enforcement

  To enforce the so-called thread means that when certain conditions are satisfied after, an object could have been a thread from monopolizing resources, program execution until the end of the thread.
Example: observe the execution of a program is not mandatory

public class ThreadDemo {
   public static void main(String[] args) throws Exception {
       Thread thread = new Thread(() -> {
           for (int i = 0; i < 100; i++) {
               try {
                   Thread.sleep(100);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               System.out.println(Thread.currentThread().getName() + "执行、i = " + i);
           }
       }, "玩耍的线程");
       thread.start();
       for (int i = 0; i < 100; i++) {
           Thread.sleep(100);
           System.out.println("【霸道的main线程】number = " + i);
       }
   }
}

 

 This time the main thread and the child thread are performed alternately with, but now want to monopolize the main thread execution, it can be used in the method of the Thread class:

  • Enforcement: public final void join (long millis) throws InterruptedException;

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Thread mainThread = Thread.currentThread();
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                if (i == 3) {//现在霸道的线程来了
                    try {
                        mainThread.join();//霸道的线程要先执行
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行、i = " + i);
            }
        }, "玩耍的线程");
        thread.start();
        for (int i = 0; i < 100; i++) {
            Thread.sleep(100);
            System.out.println("【霸道的main线程】number = " + i);
        }
    }
}

 

 After conducting thread when enforced, be sure to get a thread of execution object before execution join () call.

Thread comity

  Thread comity worth is first let out of resources so that other threads to execute. Thread comity can use the Thread class provided:

  • public static void yield ();
    Example: operation using Polite

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                if(i%3==0){
                    Thread.yield();//线程礼让
                    System.out.println("### 玩耍的线程礼让执行 ###");
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行、i = " + i);
            }
        }, "玩耍的线程");
        thread.start();
        for (int i = 0; i < 100; i++) {
            Thread.sleep(100);
            System.out.println("【霸道的main线程】number = " + i);
        }
    }
}

When comity performed every call to yield () method will only comity once the current resource.

Thread priority

  Theoretically speaking, the higher the priority of the thread, the more likely to perform (more likely to seize the resource). Thread class in the following two processing method provides for priority operations:

  • Set Priority: public final void setPriority (int newPriority);

  • Get priority: public final int getPriority ();
      when in JinXianJi are defined by digital type int done, and for this, the number selected on the Thread class defines three constants:

  • Highest priority: public static final int MAX_PRIORITY = 10;

  • Medium priority: public static final int NORM_PRIORITY = 5;

  • Lowest priority: public static final int MIN_PRIORITY = 1 ;
    Example: Observation priority

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Runnable run = () -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行。");
            }
        };
        Thread threadA = new Thread(run, "线程对象A");
        Thread threadB = new Thread(run, "线程对象B");
        Thread threadC = new Thread(run, "线程对象C");
        threadA.setPriority(Thread.MIN_PRIORITY);
        threadB.setPriority(Thread.MIN_PRIORITY);
        threadC.setPriority(Thread.MAX_PRIORITY);
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

 The main method is a main thread, the main thread priority it? The default priority thread object it?

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        System.out.println(Thread.currentThread().getPriority());
        System.out.println(new Thread().currentThread().getPriority());
    }
}

The main thread is medium priority, and the default medium priority thread is created.

 

 

 

Published 52 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/YKWNDY/article/details/104542978