java面试题二十九 多线程数据共享问题

1 编一个程序,实现2个线程对 j 变量自增, 2个线程对 j 变量自减

2 代码如下

public class TestThread {

	public static void main(String[] args) {
		   NewThread nt=new NewThread();
	       new Thread(nt).start(); 
	       new Thread(nt).start(); 
	       new Thread(nt).start(); 
	       new Thread(nt).start();      

	}

}
class NewThread  implements Runnable 
{
   int j=0;
   String runThreadName = null;
    public  void run()
   {
    
    	    while(true)
    	     { 
    	    	 synchronized(this){
    	    		  try {
    		    			Thread.sleep(1000);
    		    			runThreadName = Operation(Thread.currentThread().getName());
    		    			System.out.println(runThreadName+" : j = " +j);
    		    		} catch (InterruptedException e) {
    		    			// TODO Auto-generated catch block
    		    			e.printStackTrace();
    		    		}
    	    	 }
	    	    
    	       
    	      }
     
     

    
   }
	public String Operation(String threadName){
		int operation  = Integer.parseInt(threadName.split("-")[1]);
		String name = null;
		switch(operation){
		 case 0: j++;name="自增线程1";break;
		 case 1: j++;name="自增线程2";break;
		 case 2: j--;name="自减线程3";break;
		 case 3: j--;name="自减线程4";break;
		}
		
		return name;
	}
}


 

你可能感兴趣的:(java面试题二十九 多线程数据共享问题)