我对多线程有一个想法,但我从未尝试过。因此,当我看到我的应用程序在工作时...我还没有看到任何扩展Thread创建类的类Thread
。因此,synchronized
当2个对象尝试同时访问一个变量时,将使用关键字。.我们使用同步以避免冲突。
例子:
public class Test {
private static int count = 0;
public static synchronized void incrementCount() {
count++;
}
}
如果测试类被某个对象使用,则将添加synchronized
到中是有意义的incrementcount()
。但是,如果您不扩展Thread
,Runnable
那么写作有什么用synchronized
?
一个类不需要extend Thread
或implements Runnable
将其方法标记为已同步,以防止多线程访问
您的类可能是某个其他线程类的参数,并且该线程类可能具有多个实例。为了提供强大的数据一致性,您已经保护了代码和数据的关键部分。
只需更改您的代码示例,如下所示。
我是synchronized
在对象级别而非类级别(static synchronized
)演示
class Test {
private int count = 0;
public void incrementCount() {
count++;
System.out.println("Count:"+count);
}
}
class MyRunnable implements Runnable{
private Test test = null;
public MyRunnable(Test t){
this.test = t;
}
public void run(){
test.incrementCount();
}
}
public class SynchronizedDemo{
public static void main(String args[]){
Test t = new Test();
for ( int i=0; i<10; i++){
new Thread(new MyRunnable(t)).start();
}
}
}
您的课程Test
已作为参数传递给thread MyRunnable
。现在,您已经创建了多个线程实例。在没有synchronized
关键字的情况下,输出是不可预测的,如下所示。
java SynchronizedDemo
Count:2
Count:3
Count:2
Count:7
Count:6
Count:5
Count:4
Count:10
Count:9
Count:8
如果我改变
public void incrementCount() {
至
public synchronized void incrementCount() {
输出为:
Count:1
Count:2
Count:3
Count:4
Count:5
Count:6
Count:7
Count:8
Count:9
Count:10
另一方面,您将方法设为static synchronized
。That means lock is maintained at class level instead of object level.
请查看oracle文档页面以更好地理解。
缺少“ static synchronized
”的代码演示
class Test {
private static int count = 0;
public static void incrementCount() {
count++;
System.out.println("Count:"+count);
}
}
class MyRunnable implements Runnable{
private Test test = null;
public MyRunnable(Test t){
this.test = t;
}
public void run(){
test.incrementCount();
}
}
public class SynchronizedDemo{
public static void main(String args[]){
for ( int i=0; i<10; i++){
Test t = new Test();
new Thread(new MyRunnable(t)).start();
}
}
}
输出:
Count:5
Count:4
Count:3
Count:2
Count:10
Count:9
Count:8
Count:7
Count:6
制作后
public static void incrementCount() {
至
ppublic static synchronized void incrementCount() {
输出:
Count:1
Count:2
Count:3
Count:4
Count:5
Count:6
Count:7
Count:8
Count:9
Count:10
在此示例中,与之前不同,我们创建了10个不同的Test
实例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句