Multithreading in Java

Java provides a Thread class and a Runnable interface for threads. Both include a run () method to execute threads. Common methods are listed as follows:

Thread creation and stopping

You can create a new thread class by inheriting the Thread class, or you can create a new class by implementing the Runnable interface. The thread has a name attribute to identify it, you can call the setName () method to set it, or you can call the constructor when you create a new Thread object and pass in a string to name the thread. You can use getName () to get the name of the thread in the Thread class. There is no such method for implementing Runnable. You can use Thread.currentThread (). GetName () to get the name. Whether you inherit the Thread class or implement the Runnable interface, you need to overload the run () method and define the operations performed by the thread in run (). After the thread object is created, the content of run () will be executed by calling the start () method.

The stop of the thread cannot use stop () or interrupt (), but the flag should be set in the child thread to control the execution of the thread. For example, the sub-thread is controlled by the volatile variable in the sub-thread. If you need to stop, you can access the variable in the main process and set it to false to end the loop. In this way, the child process can continue to execute the content afterwards, perform cleaning work, etc., and then end the child process.

As shown below, two low-level threads thread1 and thread2 are first created in the main process, and are executed alternately after being started by start (). Each execution will yield the processor through yield () and compete again. Then use runFlag to manually stop two low-level threads, and then create and execute high-level threads highThread. Finally, wait for the end of highThread execution to end the main process.

//低级进程类
public class LowThread implements Runnable {//通过实现接口来新建线程类
    volatile boolean runFlag = true;     //通过标记来控制循环的执行
    @Override
    public void run() {
        int count = 1;
        String threadName=Thread.currentThread().getName();
        while (runFlag) {
            System.out.println(threadName + "线程循环次数:" + count++);
            Thread.yield();             //每循环一次让出处理器,重新和其他线程竞争处理器
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(threadName+"执行结束");
    }
}

//高级进程类
public class HighThread extends Thread { //通过继承Thread类来新建一个线程类

    public void run() {
        System.out.println(getName() + "执行!");    //Thread类内通过getName()获取线程名
    }
}

//主进程
public class RunThread {
    public static void main(String[] args) throws InterruptedException {
        LowThread thread1Run=new LowThread();   //新建RUnnable对象
        Thread thread1=new Thread(thread1Run,"线程1");        //使用Runnable对象初始化Thread
        thread1.start();                 //线程启动,自动执行run()方法

        LowThread thread2Run=new LowThread();
        Thread thread2=new Thread(thread2Run,"线程2");
        thread2.start();
        Thread.sleep(50);       //主线程休眠让出处理器,让thread1和2使用处理器执行

        System.out.println("高级线程切入");
        thread1Run.runFlag=false;       //在线程外通过volatile变量控制低级线程停止
        thread2Run.runFlag=false;
        HighThread highThread=new HighThread();
        highThread.setName("高级别线程");
        highThread.start();
        highThread.join();          //让其他线程等待直到高级线程执行结束,否则会先执行主线程,输出下一句
        System.out.println("主线程执行结束");
    }
}

The running status is shown below. You can see that the high-level process ends first, and the child process stops after the main process. You can do related cleaning and other work.

Thread mutual exclusion and synchronization

Java controls access to critical resources by creating a new Object lock. Synchronization is controlled by the synchronized keyword. When entering the critical section, the condition is judged first, and if it is met, the entry is made, otherwise the thread is placed in the wait set wait set, and then the critical section code is executed, and notify () / notifyAll () is called after the execution is completed. Notify other processes to compete for resources again.

private final Object lockObj = new Object();

synchronized (lockObj) {

    //进入临界区的条件判断
    while (条件) {
        try {
            //条件不满足, 将当前线程放入Wait Set
            lockObj.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    //执行临界区代码
    func();
    
    //唤醒所有在lockObj对象上等待的线程
    lockObj.notifyAll();
}

 

Published 124 original articles · Like 65 · Visit 130,000+

Guess you like

Origin blog.csdn.net/theVicTory/article/details/104206888