在java中使用右移运算符时,我遇到了一个奇怪的情况.当我将16向右移位31时,它会导致0然而在尝试右移16乘32时它仍然是16.有人可以解释一下,因为我疯了.
public class RightShiftTest {
public static void main(String args[]) {
int b = 16;
System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b));
// As expected it is 0
System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31));
// But why is it not 0 but 16
System.out.println("After right-shifting " + b + " for 32 times the value is " …Run Code Online (Sandbox Code Playgroud) 我在某处读到:
如果静态同步方法位于不同的类中,则一个线程可以在每个类的静态同步方法内执行.每个类一个线程,无论它调用哪个静态同步方法.
假设我有以下类层次结构:
public class Base {
public static synchronized void printBase() {
System.out.println("Inside Base");
}
}
public class Derived extends Base {
public static synchronized void printDerived() {
System.out.println("Inside Derived");
}
}
Run Code Online (Sandbox Code Playgroud)
1)如果我有以下两个函数调用:
Base.printBase();
Derived.printDerived();
Run Code Online (Sandbox Code Playgroud)
据我所知,他们不应该相互阻止,两者都可以同时执行.因为呼叫是用不同的类进行的.
2)但是,如果我有两个函数调用:
Derived.printBase();
Derived.printDerived();
Run Code Online (Sandbox Code Playgroud)
当它们在同一个类上调用时,它们应该被彼此阻塞.对?
或者还有更多的东西吗?
我是 Java 新手,在了解 Java 中的多线程时遇到了这个链接:http: //tutorials.jenkov.com/java-concurrency/slipped-conditions.html 。
在本教程中,以下代码被称为避免出现滑倒情况的良好实践:
public class Lock {
private boolean isLocked = true;
public void lock(){
synchronized(this){
while(isLocked){
try{
this.wait();
} catch(InterruptedException e){
//do nothing, keep waiting
}
}
isLocked = true;
}
}
public synchronized void unlock(){
isLocked = false;
this.notify();
}
}
Run Code Online (Sandbox Code Playgroud)
我的疑问是,如果两个线程 A 和 B 同时调用 lock() 并且 isLocked 为 true,即锁已被其他线程 C 占用。现在:
--1 A 首先进入同步块(因为只有一个人可以获得监视对象 this 的锁并进入同步块) --2 A 调用 this.wait() 并释放监视对象 this 的锁(wait() 调用)释放监视器对象上的锁http://tutorials.jenkov.com/java-concurrency/thread-signaling.html#wait-notify)但仍保留在同步块内 --3 现在 B 进入同步块(因为 A …
我对 Java 中的运算符重载有疑问。我知道Java不支持运算符重载,但是“+”运算符在下面有效的Java程序中做什么:
import java.util.*;
import java.lang.*;
import java.io.*;
class OperatorOverloadingTest
{
public static void main (String[] args) throws java.lang.Exception
{
String str1 = "Operator ";
String str2 = "overloading";
String str3 = str1+str2;
System.out.println(str3);
}
}
Stdout:
Operator overloading
Run Code Online (Sandbox Code Playgroud)