现在的位置: 首页 > 综合 > 正文

Java thread synchronized

2013年08月14日 ⁄ 综合 ⁄ 共 1072字 ⁄ 字号 评论关闭

 

 

public class Test implements Runnable{
  
    
public int x;
    
      // public synchronized void run()
    
public void run() {
    System.
out.println("threading running ..." + Thread.currentThread().getName());
    
int hold ;
    
//synchronized(this)
    {
        
for(;;){
    
            hold 
= x + 1 ;
            
try{
            Thread.sleep(
5000);
            }
catch(Exception e){
            e.getCause();
            }

            x 
= hold;
            System.
out.println(Thread.currentThread().getName()+" value x: " + x);
        }

    }

    
    }

    
    
public static void main(String[] args) {
    System.
out.println("threading ...");
    Test test1 
= new Test();
    Thread one 
= new Thread(test1);
    Thread two 
= new Thread(test1);
    one.start();
    two.start();
    }

}

 

threading ...
threading running ...Thread-0
threading running ...Thread-1
Thread-0 value x: 1
Thread-1 value x: 1
Thread-0 value x: 2
Thread-1 value x: 2
Thread-0 value x: 3
Thread-1 value x: 3
Thread-0 value x: 4
Thread-1 value x: 4
Thread-0 value x: 5
Thread-1 value x: 5
Thread-0 value x: 6
Thread-1 value x: 6
Thread-0 value x: 7
Thread-1 value x: 7

 

抱歉!评论已关闭.