简体   繁体   English

如果我没有同步这个方法,我会得到错误的值?

[英]If I don't synchronize this method I'll get wrong values?

public static int getCRC16(byte[] bytes) {
    CRC16 crc = new CRC16();
    crc.reset();
    crc.update(bytes, 0, bytes.length);
    return (int) crc.getValue();
}

Tons of threads will hit this method, if I don't synchronize I'll get a wrong crc for a specific thread? 大量的线程会遇到这种方法,如果我不同步我会得到一个特定线程的错误的crc

No, it is fine, as long as you don't use any shared variables. 不,没关系,只要你不使用任何共享变量。 The bytes and crc are local per thread. bytescrc是每个线程的本地。 That's why they are called local variables. 这就是为什么它们被称为局部变量。

This is a static method. 这是一种static方法。 Usually you need to worry about thread safety when you're dealing with the state of an object. 通常,当您处理对象的state时,您需要担心thread safety For example, if you were changing values inside the CRC16 class itself, but you're not. 例如,如果您正在更改CRC16类本身内部的值,但您不是。 Your function just takes an input bytes and returns an output crc.getValue() . 您的函数只接受输入bytes并返回输出crc.getValue()

扩展其他答案,线程扩展关于可见性和范围的Java语言,仅关于代码的执行模式,这意味着只需要一个对象可以访问的值或者只在本地有效的值不需要同步 - 仅如果在多个对象之间共享值(类的静态字段,或者所有访问者返回相同对象的单例实例),则同步值得哲学化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果我不知道必须执行多少次,如何多次调用子类的方法? - How to call a subclass' method more than once if I don't know how many times I'll have to do that? 我的二叉搜索树不打印值,不知道是打印方式还是添加方式有问题 - My binary search tree won't print the values, and I don't know whether its the printing method or the adding method that's wrong 如果我不知道我将传入多少参数,如何使用预准备语句? - How do I use a prepared statement if I don't know how many parameters I'll be passing in? 我在 sleep() 时中断了方法并且没有异常 - I interrupted method when it sleep() and don't get an exception 值不会插入数据库,即使我没有任何错误 - Values don't get inserted into the DB, even tho I don't get any errors Java:我无法让它循环,布尔值有问题,但我不知道如何修复它 - Java: I can't get it to loop, somethings wrong with the boolean but I don't know how to fix it 为什么我没有得到除 1 以外的 'a' 值的输出? - why don't i get the out put for values of 'a' other than 1? 重写图像后为什么我没有得到相同的值? - Why don't I get the same values after rewriting an image? 我不知道怎么了 - I don't know what's wrong 我应该同步我的方法吗? - Should I synchronize my method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM