<p>我想我可以声明,这个问题是由于使用Python执行环境w.r.t.Java时lambda的不同行为引起的。在</p>
<p>我有时间设置了一个简单的lambda函数,它都是用javaadpython实现的。该函数只生成一个线程,该线程在while循环中打印当前时间。问题是:Java实现中的线程是否会在lambda函数返回后继续打印,相反,Python线程是否会停止?在这两种情况下,答案都是肯定的:java线程将继续打印直到配置的超时,而python将在lambda函数返回时立即停止。在</p>
<p>Java版本的CloudWatch日志确认:</p>
<pre><code>09:55:21 START RequestId: b70e732b-e476-11e6-b2bb-e11a0dd9b311 Version: $LATEST
09:55:21 Function started: 1485510921351
09:55:21 Pre function call: 1485510921351
09:55:21 Background function: 1485510921352
09:55:21 Background function: 1485510921452
09:55:21 Background function: 1485510921552
09:55:21 Background function: 1485510921652
09:55:21 Background function: 1485510921752
09:55:21 Post function call: 1485510921852
09:55:21 Background function: 1485510921853
09:55:21 END RequestId: b70e732b-e476-11e6-b2bb-e11a0dd9b311
09:55:21 REPORT RequestId: b70e732b-e476-11e6-b2bb-e11a0dd9b311 Duration: 523.74 ms Billed Duration: 600 ms Memory Size: 256 MB Max Memory Used: 31 MB
09:55:21 Background function: 1485510921953
09:55:22 Background function: 1485510922053
...
</code></pre>
<p>在Python版本中:</p>
^{pr2}$
<p>以下是两个函数的代码:</p>
<p><strong>Python</strong></p>
<pre><code>import thread
import datetime
import time
def background_call():
while True:
print 'background_call function: %s' % (datetime.datetime.now(), )
time.sleep(0.1)
def lambda_handler(event, context):
print 'Function started: %s' % (datetime.datetime.now(), )
print 'Pre function call: %s' % (datetime.datetime.now(), )
thread.start_new_thread(background_call, ())
time.sleep(0.5)
print 'Post function call: %s' % (datetime.datetime.now(), )
return 'Needs more cowbell!'
</code></pre>
<p><strong>Java</strong></p>
<pre><code>import com.amazonaws.services.lambda.runtime.*;
public class BackgroundTest implements RequestHandler<RequestClass, ResponseClass> {
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
public ResponseClass handleRequest(RequestClass requestClass, Context context) {
System.out.println("Function started: "+System.currentTimeMillis());
System.out.println("Pre function call: "+System.currentTimeMillis());
Runnable r = new Runnable() {
public void run() {
while(true){
try {
System.out.println("Background function: "+System.currentTimeMillis());
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Post function call: "+System.currentTimeMillis());
return new ResponseClass("Needs more cowbell!");
}
}
</code></pre>