java - 关于多线程的Java初学者问题
问题描述
在多年不使用它之后,我正在提高我的 Java 技能。最近,我一直在阅读有关多线程的一章,其中提到:
“但是——如果你有一个访问静态字段的非静态方法怎么办?或者一个访问非静态字段的静态方法(使用实例)?在这些情况下,事情开始很快变得混乱,而且有一个非常好的事情不会按照你想要的方式工作的可能性。如果你有一个访问非静态字段的静态方法,并且你同步该方法,你会获得 Class 对象的锁。但是如果有另一个方法也访问非静态字段,这次使用非静态方法?它可能会在当前实例(this)上同步。请记住,静态同步方法和非静态同步方法不会相互阻塞——它们可以运行在同时。 ”
为了学习,我一直在尝试编写一个示例,其中在上面的片段中引用了一个场景:一个程序,其中一个静态同步方法修改一个非静态字段,同时运行一个非静态字段。同步方法。
所以,到目前为止,我没有成功地做到这一点。一点帮助表示赞赏。谢谢!
下面是我完成的代码示例。但是,正如预期的那样,线程不会同时运行,因为它们是同步的。我只是想看看书中提到的一个例子,这样我就知道不该做什么了。
class code147_class1{
int num1 = 111;
static int num2 = 222;
}//code147_class1
public class code147 implements Runnable {
code147_class1 z = new code147_class1();
public static void main (String args[]){
System.out.println("Program has started...");
System.out.println("The value of the instance variable is:"+new code147_class1().num1);
System.out.println("The value of the static variable is:"+code147_class1.num2);
code147 cd1 = new code147();
Thread thread1 = new Thread(cd1);
Thread thread2 = new Thread(cd1);
thread1.start();
thread2.start();
}//main
public void run(){
System.out.println("Thread has started for:"+Thread.currentThread().getId());
try{
subtract_instance_var(z);
Thread.sleep(100);
code147.static_subtract_instance_var(z);
}
catch(Exception ex){
}
}//run
public synchronized void subtract_instance_var(code147_class1 x){
if(x.num1 ==111){
try{
Thread.sleep(100);
}
catch(Exception ex){
}
x.num1 = x.num1 - 11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
}//if
System.out.println("The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);
}//subtract_instance_var
public synchronized static void static_subtract_instance_var(code147_class1 x){
if (x.num1==111){
try{
Thread.sleep(100);
}
catch(InterruptedException ex){
}//catch
x.num1 = x.num1 -11;
System.out.println("Value is subtracted at thread:"+Thread.currentThread().getId());
}//if
System.out.println("STATIC The value of instance variable at the end for thread: "+Thread.currentThread().getId()+" is "+x.num1);
}//stati_subtract_var
}//class
运行代码后,我期望实例变量的值为 89。但程序结果为 100。
解决方案
你得到的结果 100 是正确的。thread1 和 thread2 将同时运行。由于“subtract_instance_var”方法是同步的,因此一个线程会将变量设为 100。然后该线程将进入睡眠状态。随着锁被释放,其他线程可以执行“subtract_instance_var”。但是因为“x.num1==111”条件失败,什么都不会发生。睡眠后,当两个线程都尝试执行“static_subtract_instance_var”方法时,“x.num1==111”条件仍然失败。所以变量值保持为 100。
推荐阅读
- android-studio - Android Studio 中缺少一些 SDK 工具选项
- python - raise ValueError(ValueError: With n_samples=0, test_size=0.1 and train_size=None,
- pandas - 如何在熊猫中将 mxn 转换为 kx 2 形式的数据帧
- scala - Spark 和 Scala 代码启用 KRBLoginModule 与 system.setProperty throwing error no LoginModule found
- dax - DAX PowerPivot 中的计数
- node.js - 使用 twilio 添加自定义 callerid discord bot
- javascript - 解析 HashMap 失败,应为 Object,但遇到 Array
- java - 实现 Dijkstra 的 Java 程序不读取 txt 文件
- python - 将所有数据归一化
- c++ - 我可以使用 str.append 创建一个没有元音的新字符串吗?