Home  >  Article  >  Java  >  Java thread's implementation method of obtaining and returning values ​​(code)

Java thread's implementation method of obtaining and returning values ​​(code)

不言
不言forward
2018-10-10 11:57:092149browse

The content of this article is about the implementation method (code) of Java thread value acquisition and return. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

How to make a thread run continuously and return the value when it gets the value so that the thread can continue running?

We all know that we can use the Callable interface to obtain the return value of the thread, or trigger event monitoring to operate the return value. I will introduce another method below.

public abstract class Test implements Runnable {
    public String A;

    //开启线程
    public void run() {
        while(true) {
            //此处写该方法的逻辑代码
            
            //listen()方法操作取得值A
            listen(A);
            
        }

    }

    //定义一个抽象方法listen()
    public abstract void listen(String A);

}

In this way, the value obtained by the thread will be stored in the abstract method listen(), and the thread will keep running without stopping.

When we need to use this value, we only need to override the listen() method.

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new Test() {
            
            @Override
            public void listen(String A) {
                // TODO Auto-generated method stub
                
            }
        });
        thread.start();
    }
}

The above is the detailed content of Java thread's implementation method of obtaining and returning values ​​(code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete