小编abh*_*aug的帖子

为什么在Java中右移16×32导致16而不是0?16 >> 32 = 16为什么?

在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)

java

4
推荐指数
1
解决办法
581
查看次数

java中继承下的同步静态方法行为

我在某处读到:

如果静态同步方法位于不同的类中,则一个线程可以在每个类的静态同步方法内执行.每个类一个线程,无论它调用哪个静态同步方法.

假设我有以下类层次结构:

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 static multithreading synchronized

3
推荐指数
1
解决办法
344
查看次数

多个线程不能同时进入同步块吗?

我是 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 multithreading synchronized locks

2
推荐指数
1
解决办法
1013
查看次数

Java,运算符重载和字符串的“+”运算符

我对 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)

java string operator-overloading

2
推荐指数
1
解决办法
2041
查看次数