`

线程同步2

    博客分类:
  • JAVA
 
阅读更多
如果某个synchronized 方法是static 的,那么当线程访问该方法时,
它锁的并不是synchronized方法所在的对象,而是synchronized方
法所在的对象所对应的Class 对象,因为Java中无论一个类有多少个
对象,这些对象会对应唯一一个CLASS对象,因些当线程分别访问
同一个类的两个对象的两个static,synchronized方法时,他们的执行
顺序的,也就是说一个线程先去执行方法,执行完毕后另一个线程
在执行。

-------------------------------------------------
package thread;

public class ThreadTest4 {
public static void main(String[] args) {
Example example = new Example();

TheThread thread = new TheThread(example);
example = new Example();
TheThread2 thread1 = new TheThread2(example);

thread.start();

thread1.start();

}
}

class Example {

public  static void execute() {

for(int i = 0; i < 20 ;i++) {
System.out.println("hello: "+i);
}
}
public  synchronized static void execute2() {

for(int i = 0; i < 20 ;i++) {
System.out.println("word: "+i);
}
}
}

class TheThread extends Thread {

private Example example;

public TheThread(Example example) {
this.example = example;
}

@Override
public void run() {
// TODO Auto-generated method stub
example.execute();
}
}
class TheThread2 extends Thread {

private Example example;

public TheThread2(Example example) {
this.example = example;
}

@Override
public void run() {
// TODO Auto-generated method stub
example.execute2();
}
}

结果:
--------------------------------------------------
hello: 0
hello: 1
word: 0
hello: 2
word: 1
hello: 3
word: 2
hello: 4
word: 3
word: 4
word: 5
word: 6
word: 7
word: 8
word: 9
word: 10
word: 11
word: 12
word: 13
word: 14
word: 15
word: 16
word: 17
hello: 5
hello: 6
hello: 7
hello: 8
hello: 9
hello: 10
hello: 11
hello: 12
hello: 13
hello: 14
hello: 15
hello: 16
hello: 17
hello: 18
hello: 19
word: 18
word: 19
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics