JAVA multi-threaded (basic)

1. processes and threads

1.1 The concept of processes and threads

Process concept : the operating system execution cycle of a program (for example: open and close the qq qq This is a process)

                 Process is the operating system resource allocation smallest unit

Thread concept a task process:

                 A thread is the operating system resource scheduling smallest unit

Processes and threads difference :

  • Address space: the same threads in the process shared address space of this process, but the process is independent of address space
  • Memory resources: The same process threads share the resources of this process, memory (memory heap and method area, stack memory is not shared), while resource processes are independent of each other
  • Both can be executed concurrently (alternately switching multiple tasks to perform)

1.2 thread state

Create, ready, running, blocking, termination

2. multithreading

2.1 Thread class inheritance (implements Runnable interface)

Example:

class MThread extends Thread{
    private String cat;
    public MThread(String cat){
        this.cat = cat;
    }
    public void run(){
        for(int i = 0; i < 5;i++){
            System.out.println(this.cat+"喜欢"+i);
        }
    }
}
public class MyThread {
    public static void main(String[] args) {
        Thread thread1 = new MThread("小花");
        Thread thread2 = new MThread("小白");
        Thread thread3 = new MThread("桔子");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

Why call the start () method instead of run () method?

  • run () method is a convention multithreaded programs. All multithreaded code in the run method inside.
  • Call start () method, the thread will automatically call the run () method
  • start () method to start a thread, truly multi-threaded operation, this time without waiting for the run method body code is completed and proceed directly to the following code:
  • Call start Thread class () method to start a thread, then this thread is ready (to run) state, and is not running, Once cpu time slice, they begin to execute run () method.
  • run () method is just a common method of the class, if you call the Run method directly, the program is still only the main thread of this thread, the program execution is only one path, or to execute the order, or to wait for the run is finished after the method body You can continue to execute the following code, so there is no purpose to write thread.

2.1 implement Runnable

Example 1:

class MThread implements Runnable{
    private String cat;
    public MThread(String cat){
        this.cat = cat;
    }
    public void run(){
        for(int i = 0; i < 5;i++){
            System.out.println(this.cat+"喜欢"+i);
        }
    }
}
public class MyThread {
    public static void main(String[] args) {
        Mthread thread1 = new MThread("小花");
        Mthread thread2 = new MThread("小白");
        Mthread thread3 = new MThread("桔子");
        new Thread(thread1).start();
        new Thread(thread2).start();
        new Thread(thread3).start();
    }
}

Example 2: Using an anonymous inner classes

public class MyThread {
    public static void main(String[] args) {
        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("小花最调皮");
            }
        }).start();
    }
}

Example Three: Using Lamdba expression

public class MyThread {
    public static void main(String[] args) {
        Runnable runnable = ()-> System.out.println("小花最调皮");
        new Thread(runnable).start();
    }
}

Thread and Runnable difference of (Runnable advantage)

  • Implement Runnable easier to share resources
  • Avoiding the limitations of single inheritance
  • Into the thread pool can only achieve Runnable, Callable Class interface, not directly into the class inheritance Thread

 

2.3 implement Callable Interface

class Mthread implements Callable{
    private int cat = 4;
    @Override
    public Object call() throws Exception {
        while(cat > 0){
            System.out.println("还有"+cat+"只猫");
            cat--;
        }
        return "猫咪回家了,撸猫明请早";
    }
}
public class MyThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> callable = new FutureTask<>(new Mthread());
        new Thread(callable).start();
        System.out.println(callable.get());
    }
}

The run Runnable () method does not return a value, but often requires some return value, for example, might bring back some threads execute complete some returns the result, in which case it can only be achieved multi-threaded use Callable.

Common methods of operation 3. Multi-threaded

3.1 thread naming and made

If no thread name, the thread is automatically assigned a name

  • public final synchronized void setName (String name); // create a thread when setting name
  • public Thread (Runnable target, String name); // Set the thread name
  • public final String getName (); // get the thread name
public class MyThread{
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                //设置线程名称
                this.setName("小白");
                System.out.println(this.getName());
            }
        }.start();
        //通过构造方法设置名称
        new Thread("小花"){
            public void run(){
                System.out.println(this.getName());
            }
        }.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获得当前线程名称
                System.out.println(Thread.currentThread().getName());
            }
        }).start();
    }
}

3.2 thread to sleep (sleep method)

SLEEP () : thread to suspend it, to a predetermined time before continuing. In the meantime, we will hand over the right to use the CPU, but will not release the lock. In other words, if the current thread holds a lock on an object, then the sleep, other threads can not access this object. And after this method is called, the thread back to blocking state.

  • public static native void sleep(long millis) throws InterruptedException
class MThread implements Runnable {
    private String cat;
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "喜欢" + i);
        }
    }
}

3.3 thread concessions (yield method)

yield () : Pauses the current thread of execution in favor of other threads to execute. We will hand over the right to use the CPU, but can not hand over control of a specific time. And calling this method does not release the lock. And after this method is called, the thread back to the ready state.

class MThread implements Runnable {
    private String cat;
    public void run() {
        for (int i = 0; i < 5; i++) {
                Thread.yield();
            System.out.println(Thread.currentThread().getName() + "喜欢" + i);
        }
    }
}

3.4join () method

the Join () : Waits for this thread. It said the thread must wait after executing the order execution threads to be executed.

public class MyThread{
    public static void main(String[] args) {
       Thread thread1 = new Thread(new Runnable() {
           @Override
           public void run() {
               for (int i = 0;i < 5;i++){
                   System.out.println(Thread.currentThread().getName());
               }
           }
       });
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                for (int i = 0;i < 5;i++){
                    try {
                        thread1.join();
                        System.out.println(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread1.start();
        thread2.start();
    }
}

3.5 thread stops

  • Flag is set, the thread may be normal exit.
class MThread implements Runnable {
    private boolean flag = true;
    @Override
    public void run() {
        int i = 1;
        while (flag) {
            try {
                Thread.sleep(1000);
                System.out.println("第"+i+"次执行,线程名称为"+Thread.currentThread().getName());
                i++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
public class MyThread{
    public static void main(String[] args) throws InterruptedException {
        MThread myThread = new MThread();
        new Thread(myThread).start();
        Thread.sleep(4500);
        myThread.setFlag(false);
    }
}
  •  Stop method to force the thread exits (deprecated)

stop method will release all locking threads obtained when the stop method is called, the thread object thread running will stop immediately, and therefore may produce incomplete disability data.

  •  Use a interrupt Thread class () can interrupt thread.

interrupt () method simply changing the interrupt status only, it will not interrupt a running thread.

class MThread implements Runnable {
    @Override
    public void run() {
        boolean bool = Thread.currentThread().isInterrupted();
        while (!bool){
            try {
                Thread.sleep(1000);
                System.out.println("阻塞情况下"+bool);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

3.6 thread priority

  •  Highest priority: public final static int MAX_PRIORITY = 10;
  • Medium priority: public final static int NORM_PRIORITY = 5;
  • Lowest priority: public final static int MIN_PRIORITY = 1;
  • Set priorities: public final void setPriority (int newPriority)
  • Get priority: public final int getPriority ()
class MThread implements Runnable {
    @Override
    public void run(){
            System.out.println(Thread.currentThread().getPriority());
    }
}
public class MyThread{
    public static void main(String[] args) throws InterruptedException {
        MThread mt = new MThread();
        Thread t1 = new Thread(mt,"1") ;
        Thread t2 = new Thread(mt,"2") ;
        Thread t3 = new Thread(mt,"3") ;
        t1.setPriority(6);
        t2.setPriority(Thread.MIN_PRIORITY);
        t3.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }

3.7 daemon thread

java There are two threads: the user thread and thread guard

Typical daemon thread to thread garbage collection, as long as there is any non-daemon current JVM process has not ended, then the daemon should have been working. Only when the last non-daemon thread executed, the daemon thread will be closed

Can be distinguished by isDaemon () method

class MThread implements Runnable {
    @Override
    public void run(){
            System.out.println(Thread.currentThread().isDaemon());
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43573534/article/details/90037608