首页 \ 问答 \ 何时ThreadLocal优先于局部变量?(When is ThreadLocal preferred over Local Variables?)

何时ThreadLocal优先于局部变量?(When is ThreadLocal preferred over Local Variables?)

Java中的ThreadLocal说:

Java中的ThreadLocal类使您可以创建只能由同一线程读取和写入的变量。 因此,即使两个线程正在执行相同的代码,并且代码具有对ThreadLocal变量的引用,那么这两个线程也看不到彼此的ThreadLocal变量。

我的问题是:当我们需要获取一个特定于线程的变量时,我们不能只将该变量声明为方法中的局部变量吗? 因为每个线程都有自己的堆栈,因此它获得了自己的变量副本。 我在这里错过了什么吗?


ThreadLocal in Java says that:

The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

My question is: When we need to get a variable specific to a thread, can't we just declare that variable as a local variable inside a method? Because every thread has its own stack and thus it gets its own copy of variables. Am I missing something here?


原文:https://stackoverflow.com/questions/38448292
更新时间:2023-10-28 09:10

最满意答案

最好的解决方案是在服务器端安装denver并使用PHP代码。

这是js文件中的代码。

  deleteNewsItem: function(newsId, callback, scope) {
     var dataPath = this.dataPath;
      $.getJSON(dataPath + '/delete-news.php?id='+newsId, function(rawHeadlines) { 
         var headlines = [];
         $.each(rawHeadlines, function(index, rawHeadline) {
            headlines.push(rawHeadline.id);
        } 
     });
             if (callback) {
             callback.call(scope, headlines);
     }
     };

这是“delete_news.php”文件中的代码。

<?php

$deleteId = isset($_GET['id'])?$_GET['id']:false;
   if ($deleteId){
     $content = file_get_contents('delete-news.json');
     $json = json_decode($content);

$newData = array();
foreach($json as $key=>$id){
$newData []= (array)$id;
}
$newData []= array("id"=>(int)$deleteId);


$fill_view = json_encode($newData);
file_put_contents('delete-news.json', ($fill_view));
echo $fill_view;
} else {
echo json_encode(array());
}
exit();

?>

The best solution was to install denver and use PHP code on server-side.

This is code in the js file.

  deleteNewsItem: function(newsId, callback, scope) {
     var dataPath = this.dataPath;
      $.getJSON(dataPath + '/delete-news.php?id='+newsId, function(rawHeadlines) { 
         var headlines = [];
         $.each(rawHeadlines, function(index, rawHeadline) {
            headlines.push(rawHeadline.id);
        } 
     });
             if (callback) {
             callback.call(scope, headlines);
     }
     };

This is the code in the "delete_news.php" file.

<?php

$deleteId = isset($_GET['id'])?$_GET['id']:false;
   if ($deleteId){
     $content = file_get_contents('delete-news.json');
     $json = json_decode($content);

$newData = array();
foreach($json as $key=>$id){
$newData []= (array)$id;
}
$newData []= array("id"=>(int)$deleteId);


$fill_view = json_encode($newData);
file_put_contents('delete-news.json', ($fill_view));
echo $fill_view;
} else {
echo json_encode(array());
}
exit();

?>

相关问答

更多
  • 我想到了... 这可能会帮助像我一样的新手,他们犯了同样的错误,所以我会回答我自己的问题:) 原来我没有登录,去图。 虽然这个回应很奇怪,并且帮助我抛弃了整个主页。 原因是我阻止了我的函数文件,其中包含Ajax响应者,如下所示: function block_users() { if( !current_user_can( 'delete_pages' ) ) { wp_redirect( get_home_url(), 301 ); exit; } } ...
  • 我终于找到了问题的解决方案,这个问题很简单但完全不明显。 事实证明,我试图反序列化的Model对象是在一个名称不正确的包中,当Spring无法找到Model时,它只是吞下生成的异常并返回false。 我通过在Spring-MVC中深入调试,特别是StdDeserializerProvider类来发现这一点。 对于那些收到此错误的人,我强烈建议编写一些代码来验证此类中发生的情况,例如: @Test public void testThatCanConvertUpdateModel() { MappingJ ...
  • 在发布复杂数据时,您应该在将contentType指定为application/json同时发送对象的JSON字符串化版本 您可以使用JSON.stringify方法将数组转换为相应的json字符串。 var data = []; data.push({ Company: "Microsoft", Location: "Redmond" , Total:123 }); data.push({ Company: "UrbanScience", Location:"Detroit", Total:456 }); ...
  • 最好的解决方案是在服务器端安装denver并使用PHP代码。 这是js文件中的代码。 deleteNewsItem: function(newsId, callback, scope) { var dataPath = this.dataPath; $.getJSON(dataPath + '/delete-news.php?id='+newsId, function(rawHeadlines) { var headlines = []; $. ...
  • allFunctions.php: if ($_POST['candy']) { allFunctions::giveCandy(); } class allFunctions { static function giveCandy () { $db = Database::getInstance(); // .... JS: $(document).ready(function () { $('#button_candy').subm ...
  • 正如@georgeawg建议的那样,您可以使用$ http服务: $http.post('/someUrl', data, config).then(successCallback, errorCallback); 并修改你的代码为: $http.post({ 'api/pushnotification', // Post URL JSON.stringify(item), // Data to be sent contentType: 'application/ ...
  • 127.0.0.1 - - [04/Jan/2017 09:13:47] "OPTIONS /add_profile_data HTTP/1.1" 500 OPTIONS请求不包含JSON。 编辑代码以仅在方法为POST检查JSON。 例如: @app.route('/add_profile_data', methods=['POST', 'GET']) def add(): if request.method == 'POST': data = request.json ...
  • 如果您不希望返回JSON格式,则可能需要删除它。 submit(){ if(this.checkRequiredField()){ $.ajax({ url: '/api/Accounts', type: 'POST', data: { Name: this.state.name, StartDate :this.state.startDate, EndD ...
  • 最后解决了它,当你从控制器返回结果而不是返回JSON我使用了“内容(值)”。 控制器代码: public ActionResult ImportExcelData(HttpPostedFileBase UploadExcel) { try { var Data = Repository.ImportData(filePath, OrgID); if(sData!=null) { ...
  • 问题是你的函数functionRedeempoints不会返回ajax调用可以处理的任何内容。 它甚至在返回声明之前就已经消亡了。 此外,PHP端的返回将永远不会被JS解释。 JS只能读取http请求,因此您需要通过echo语句实际写入它。 Wordpress为您提供了一种方便的处理方式:您需要的是: function functionRedeempoints() { wp_send_json_success(true); } 这已经负责停止执行并正确地对您的响应进行JSON编码。 JS方面的正确响 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。