我有一堂课很好。现在,我想计算一些东西并将其记录下来,但这不应该影响性能,因此,我想创建一个线程并认为线程应该实现这一点。但是从来没有做过线程。因此,思考实现可运行和运行类。不知道我怎么能做到这一点。
class Test implements ServiceA, Runnable
{
private final ServiceA one;
private final ServiceA two;
Test(ServiceA one, ServiceA two)
{
this.one = one;
this.two= two;
}
@override
public objectA calculate(TInput input)
{
objectA objAOne = one.Find(input);
// First I just had "return one.calculate(input)";
// Now I want to create a thread and that should do 2 things.
// 1. call "two.calculate(input)" -- App Shouldnt wait for the response of this
// 2. log this (which i know).
//How can i create a thread here that can help me achieve this
return objAOne ;
}
@Override
public void run()
{
}
}
有人可以帮我吗?
答案 0 :(得分:0)
我知道在乞讨中很难理解多线程。这是一个简单的示例,可能会为您提供指导
public class MyTest {
static class MyWorker implements Runnable {
public String result = "not calculated yet";
private String params;
public MyWorker(String params) {
this.params = params;
}
@Override
public void run() {
// calculate here
this.result = "Result of calculation for " + this.params;
}
}
public static void main(String[] args) throws InterruptedException {
MyWorker w1 = new MyWorker("One");
MyWorker w2 = new MyWorker("Two");
new Thread(w1).start();
new Thread(w2).start();
System.out.println("0 w1 result: " + w1.result);
System.out.println("1 w2 result: " + w2.result);
Thread.sleep(1000);
System.out.println("2 w1 result: " + w1.result);
System.out.println("3 w2 result: " + w2.result);
}
}
可能的输出:
0 w1 result: not calculated yet
1 w2 result: not calculated yet
2 w1 result: Result of calculation for One
3 w2 result: Result of calculation for Two
Process finished with exit code 0