a multithreaded java: create a thread and multi-thread

Article Source: https://www.jianshu.com/p/ba24b782d5ca

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

Inherit Thead class implements multithreading

  There is a Java java.lang.Thread of classes, then a long succession of such class would indicate that the main thread of our class, but this class does not mean that you can achieve multi-threaded processing, because there needs to override Thread provided a class run () method, and this method belongs to the main thread method.
Example: multi-threaded body of the class

class MyThread extends Thread {//线程的主体类
    private String title;
    public MyThread(String title) {
        this.title = title;
    }
    @Override
    public void run() {//线程的主体方法
        for (int i = 0; i < 10; i++) {
            System.out.printf("%s运行.i = %s \n", this.title, i);
        }
    }

Multithreading functions to be performed should be defined in the run () method.
  It should be noted that: Under normal circumstances, if you want to use a class, then it must produce instantiate an object, and then to call methods in the class offered, but run () method is not directly invoked, because this operating system which involves resource scheduling problem, so in order to start using multithreading must start () method has completed.
Example: multi-start threads

public class ThreadDemo {
    public static void main(String[] args) {
        new MyThread("线程A").start();
        new MyThread("线程B").start();
        new MyThread("线程C").start();
    }
}

By this time you can call to find, although the call to the start () method, but ultimately do is run () method, and all objects are alternately thread of execution.
  Question: Why not start multi-threaded directly run () method must use the Thread class start () method do? If you want to clear this problem, the best approach is to look at the operation achieve start () method, it can be observed directly through source code.

   public synchronized void start() {
        if (threadStatus != 0) //判断线程的状态
            throw new IllegalThreadStateException();//抛出一个异常
        group.add(this);
        boolean started = false;
        try {
            start0();//在start()方法中调用了start0()
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            }
        }
    }
    private native void start0();//只定义了方法名称,但没有实现

 Found that start () method which will throw an exception class IllegalThreadStateException target, but the entire program and not to use throws or clearly try..catch process, because the exception must be a subclass of RuntimeException, each thread class of objects only allowed to start again, if repeated start IllegalThreadStateException exception is thrown, for example: the following code will throw an exception.

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread mt=  new MyThread("线程A");
        mt.start();
        mt.start();//重复进行了线程的启动
    }
}
Exception in thread "main" java.lang.IllegalThreadStateException

 

In the process of implementation of Java programs, taking into account the different levels of demand for developers, so it supports local operating system function calls, but this technique is called JNI (Java Native Inteface) technology, but Java development process in such use is not recommended, the use of this technique may use some of the underlying operating system functions, some Unexamined process, and provided in start0 Thread class () indicates this method relies on the need for different operating system implementation.

 

  In any case, as long as the definition of a multi-threaded, multi-threaded start is always only one program: Thread class start () method.

Runnable interface based on multi-threaded

  While it is possible to achieve the defined multi-threaded through inheritance Thread class, but in a Java program to inherit always exist limitations of single inheritance, so in Java and provides definitions form the main structure of the second multi-threading: achieve java .lang.Runnable interface, which is defined as follows:

@FunctionalInterface //从JDK1.8引入Lambda表达式后就变为了函数式的接口
public interface Runnable{
    public void run();
}

Example: multi-threaded through the body of the class Runnable

class MyThread implements Runnable {//线程的主体类
    private String title;
    public MyThread(String title) {
        this.title = title;
    }
    @Override
    public void run() {//线程的主体方法
        for (int i = 0; i < 10; i++) {
            System.out.printf("%s运行.i = %s \n", this.title, i);
        }
    }
}

  However, because now it will not inherit the Thread parent class, then for this time of MyThread class no longer supports start () method inherited this, but if you do not start () method is not multi-threaded start, then this time we need to look at the Thread class constructor provided.

       Constructor: public Thread (Runnable target);
       Example: Start multithreading

public class ThreadDemo {
    public static void main(String[] args) {
        Thread threadA=new Thread(new MyThread("线程对象A"));
        Thread threadB=new Thread(new MyThread("线程对象B"));
        Thread threadC=new Thread(new MyThread("线程对象C"));
        threadA.start();//启动多线程
        threadB.start();//启动多线程
        threadC.start();//启动多线程
    }
}

This time multithreading can be found, since only implements the Runnable interface object, so in this case the thread main class no longer has the limitations of single inheritance, this design is a standard type of design.
  JDK1.8 can be found from the beginning, Runnable interface uses a functional interface definition, so it can be used directly Lambda expressions thread class implementation.
Example: the use of multi-threaded set Lambda

public class ThreadDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            String title = "线程对象" + i;
//            Runnable run = () -> {
//                for (int j = 0; j < 10; j++) {
//                    System.out.printf("%s运行.j = %s \n", title, j);
//                }
//            };
//            new Thread(run).start();
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    System.out.printf("%s运行.j = %s \n", title, j);
                }
            }).start();
        }
    }
}

 For multi-threaded, the priority is to achieve Runnable interface in the future development and launch multi-threaded through the Thread class.

Thread relationships with Runnable

  After a series of analysis can be found, already had two approaches in the implementation process multiple threads: Thread class, Runnable interface if the code itself is concerned, certainly with Runnable is the most convenient because it can be avoided the limitations of single inheritance, colleagues can better be expanded functions.
  But we also need to observe Thread and Runnable contact from the structure, open the definition of Thead:

public class Thread extends Object implements Runnable {}

  Thread class is a subclass found Runnable interface, so that when overwriting or RUN Thread class inheritance Runnable interface (), then look at the case of the class structure of the program

class MyThread implements Runnable {//线程的主体类
    private String title;
    public MyThread(String title) {
        this.title = title;
    }
    @Override
    public void run() {//线程的主体方法
        for (int i = 0; i < 10; i++) {
            System.out.printf("%s运行.i = %s \n", this.title, i);
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Thread threadA=new Thread(new MyThread("线程对象A"));
        Thread threadB=new Thread(new MyThread("线程对象B"));
        Thread threadC=new Thread(new MyThread("线程对象C"));
        threadA.start();//启动多线程
        threadB.start();//启动多线程
        threadC.start();//启动多线程
    }
}

 

Multithreaded designs, using the proxy design pattern structure, user-defined but the main thread is responsible for implementing the project core, and all auxiliary achieve all handled by the Thread class.
  Thread start multithreading when making the call is the start () method, and then find that the run () method, but passed a Runnable interface object by Thread class constructor method, then the object will be the interface of the Thread class target attribute stored in the start () calls the run () method of the Thread performing the methods, and the run () method to be invoked Runnable interface subclass coated written run () method.
  Multithreading is essentially the essence of development is that multiple threads can grab the same resources, then Thread main thread is described, and description of the resource is done through Runnable.

Resources to implement concurrent access by multiple threads utilize ticketing program: Example

class MyThread implements Runnable {//线程的主体类
    private int ticket = 5;
    @Override
    public void run() {//线程的主体方法
        for (int i = 0; i < 100; i++) {
            if (this.ticket > 0)
                System.out.printf("卖票,ticket = %s \n", this.ticket--);
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        new Thread(mt).start();//第一个线程启动
        new Thread(mt).start();//第二个线程启动
        new Thread(mt).start();//第三个线程启动
    }
}

This procedure performed to analyze the structure of the memory by analyzing FIG.

 

Callable multi-threaded

  From the most traditional development, if you want to be sure to rely on multi-threaded Runnable, but Runnable interface has a drawback, when unable to obtain a complete implementation of the Runnable return value, so a new thread made from the realization JDK1.5 Interface: java.util.concurrent.Callable interfaces, first of all to observe this definition interface:

@FunctionalInterface
public interface Callable<V>{
    public V call() throws Exception;
}

 

  Callable definitions can be found when you can set up a generic, this generic type is the return type of data, so the advantage to avoid the downcast brings security risks.

Example: Using Callable multi-threaded processing

class MyThread implements Callable<String> {//线程的主体类
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println("*********** 线程、i = " + i);
        }
        return "线程执行完毕。";
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        FutureTask<String> task = new FutureTask(new MyThread());
        new Thread(task).start();
        System.out.println("【线程返回数据】" + task.get());
    }
}

 

Thread running state

  For the development of multi-threaded, the process of programming is always in accordance with: the definition of the thread main categories, and then start the thread through the Thread class, but that does not mean you call the start () method, the thread has already begun running because the whole process has its own set of threads running state.

1, a thread of any object Thread class should be used for packaging, it is used to start the thread Start (), but in fact, when the number of start threads are set to a state ready state, and now is not performed;
       2 , enter the ready state after waiting for resource scheduling, when a thread scheduling success into the operating state (run () method), but can not until all the threads execute down the middle need to have some paused for example: a thread after a period of time will need to perform a resource, then this thread will enter the blocking state, and then again return to the ready state.
       3, when the run () method is finished, in fact, the main task of the thread is over, so then you can go directly to stop state.

 

 

 

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

Guess you like

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