Home > Java > javaTutorial > body text

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

不言
Release: 2018-10-10 11:57:09
forward
2185 people have browsed it

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);

}
Copy after login

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();
    }
}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!