- class hello implements Runnable {
- Object obj=new Object();
- //synchronized(obj){ 如果把synchronized(obj)语句写到这里,为什么会报错呢?
- public void run() {
- for(int i=0;i<10;++i){
- synchronized(obj){
- if(count>0){
- try{
- Thread.sleep(1000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println(count--);
- } }
- }
-
- }
-
- public static void main(String[] args) {
- hello he=new hello();
- Thread h1=new Thread(he);
- Thread h2=new Thread(he);
- Thread h3=new Thread(he);
- h1.start();
- h2.start();
- h3.start();
- }
- private int count=5;
- }
复制代码 |
|