为什么ThreadLocal变量需要静态?(Why ThreadLocal variable need to static?)
我已经阅读了很多关于为什么
ThreadLocal
变量需要静态(尽管不是必需)的文章,但我没有明白为什么它应该是静态的。我在这里阅读了许多其他链接,但没有得到这个想法。
我做过类似的事
public class ThreadLocalDemo{ public static void main(String[]args)throws Exception{ SharedRersource r1= new SharedRersource(); Thread t1= new Thread(r1); Thread t2= new Thread(r1); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Main thread Exiting..."); } } class SharedRersource implements Runnable{ private ThreadLocal<Integer> threadId = new ThreadLocal(){ protected Integer initialValue(){ return (int)(Math.random()*100); } }; public void run(){ try{ Thread.sleep(2000); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println(threadId.get()); } };
这里线程t1和t2具有threadId的私有副本,而不是为什么它应该是静态的
请给我更好的理解。 谢谢
I have read many articles on why
ThreadLocal
variable need to be static(although not necessary), but I didn't get the idea why it should be static.I have read it here and many other links but didn't get the idea.
I have done something like this
public class ThreadLocalDemo{ public static void main(String[]args)throws Exception{ SharedRersource r1= new SharedRersource(); Thread t1= new Thread(r1); Thread t2= new Thread(r1); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Main thread Exiting..."); } } class SharedRersource implements Runnable{ private ThreadLocal<Integer> threadId = new ThreadLocal(){ protected Integer initialValue(){ return (int)(Math.random()*100); } }; public void run(){ try{ Thread.sleep(2000); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println(threadId.get()); } };
Here thread t1 and t2 is having private copy of threadId than why It should be static
Please give a better understanding to me. Thanks
原文:https://stackoverflow.com/questions/35764959
最满意答案
尝试这个
TableModel.objects.filter( group_id=group_id, status=1, time__range = get_time_range(range) ).annotate( period=DateTrunc('day', 'time') # Truncate to day and add to select query ).values('period') # Group By period .annotate(count=Count('status')) # add count of the grouping to select .values('period', 'count') .order_by('-time')
It can be fixed by -
SELECT 1 as id ,DATE_TRUNC('day', "table"."time") AS "period", COUNT("table"."status") AS "count" FROM "table" WHERE "table"."group_id" = '2177' and "table"."status"=1 and time >= '2017-04-28 12:48:33.348682+00:00' and time <= '2017-05-05 12:48:33.348682+00:00' GROUP BY DATE_TRUNC('day', "table"."time"),period ORDER BY period DESC limit {} offset {};
by default, django needs to return id(primary_key) field .
相关问答
更多-
你可以看看类似的讨论: 从不同类别获取最新对象的Django查询 You can take a look at similar discussion: Django Query That Get Most Recent Objects From Different Categories
-
如果您打算进行聚合,您可以使用ORM的聚合功能 : from django.db.models import Count Members.objects.values('designation').annotate(dcount=Count('designation')) 这导致一个类似于的查询 SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation 并且输出将是形式 [{'designatio ...
-
您可以使用Django聚合框架 : from django.db.models import Max, Min, Avg MyModel.objects.values('a').annotate(Min('b'), Max('b'), Avg('b')) 这里的values('a')部分基本上意味着“分组”。 You can use the Django aggregation framework: from django.db.models import Max, Min, Avg MyModel. ...
-
Django查询不分组(Django query does not group)[2023-11-24]
result = Mensaje.objects.values('remitente__username').annotate(num_msg=Count('pk')).order_by('remitente__username') 你做了order_by作为.order_by('-fechaEnvio') ,在这种情况下没有逻辑。 (您正在尝试订购带有属性( fechaEnvio )的表格,该属性不属于新生成的group_by表格) result = Mensaje.objects.values('re ... -
这将为您提供所有组中所有用户的列表: from django.contrib.auth.models import Group for group in Group.objects.all(): for user in group.user_set.all(): print '%s\t%s' % (user.username, group.name) 您还可以在一个查询中获取相同的信息: user_groups = Group.objects.values_list('user_ ...
-
我想这里的解决方案,在CONVERT_TZ EXTRACT(MONTH FROM CONVERT_TZ(`events_event`.`pay_time`, 'UTC', Africa/Cairo)) 你可以试试 class Month(Func): function = 'EXTRACT' template = "%(function)s(MONTH from CONVERT_TZ(%(expressions)s, 'UTC', 'Africa/Cairo'))" output_ ...
-
您不需要GROUP_BY ,只需使用反向外键查找 : categories = QuestionCategory.objects.prefetch_related('question_set').all() for category in categories: print category.name for question in category.question_set.all(): print question.question print ques ...
-
通过查询Django组?(Django Group by query?)[2024-02-26]
尝试这个 TableModel.objects.filter( group_id=group_id, status=1, time__range = get_time_range(range) ... -
Django查询组中的差异(Django query difference in group)[2022-01-29]
我想要所有的A,其中任何相关的模型C的X属性有20%或更多的差异 如果A的Cx中的任何一个具有%20的差异,那么该A的MAX和MIN Cx肯定具有至少%20或更大的差异。 您可以根据该事实构建查询。 使用聚合表达式,您可以执行以下操作: A.objects.annotate( max_diff=(Max('b__c__x') - Min('b__c__x')) * 100 / Min('b__c__x') ).filter(max_diff__gte=20) 当然b,c代表外国或多对多 ... -
Django GROUP BY查询(Django GROUP BY query)[2023-07-20]
def myview(request): lists = [] colors = Fruit.objects.values_list('color', flat=True).distinct() for color in colors: fruits = Fruit.objects.filter(color=color).order_by('-age')[:1] for fruit in fruits: lists.ap ...