thread_2.java

来自「java 线程 静态锁」· Java 代码 · 共 56 行

JAVA
56
字号
package thread_static_1_2_2;

class TestThread {
	public static Object lock=new Object();  //静态锁,锁类,不是锁对象了!!所以两个线程同时 运行两个 TestThread 的execute(),也可以同步!!!
		     public   void execute(){  //
			    	 synchronized(lock){ for(int i=0;i<20;i++){//和execute1() 是等效的!!!
				        	try {
								Thread.sleep(30);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				            System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+"    "+i);
					  }    
		          }
		     }
		
		     
		     public  static void execute1(){  //如果这里不加 synchronized ,则不会同步,输出还是交错的!!因为,这个static 方法不用拿到锁就可以运行!!!
		    	 for(int i=0;i<20;i++){
			        	try {
							Thread.sleep(30);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
			            System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+"    "+i);
				  }    
	          }
 }

 class ThreadA implements Runnable{
         TestThread test=null;
	    public ThreadA(TestThread pTest){  //对象有外部引入,这样 在需要的时候, 可以 保证是同一个对象,当然也可以传入不同的实例。比如下面main()。
             test=pTest;
        }
        public void run() {
            test.execute1();
}
    }
public class Thread_2{
			public static void main(String[] args){
				 TestThread test=new TestThread();//和下面的test2 生成不同的实例,也就要是 让两个线程 运行的是两个实例,再试验synchronized,
				 //
				 Runnable runabble=new ThreadA(test);
				 
				 TestThread test2=new TestThread();//
				 Runnable runabble2=new ThreadA(test2);
				
				 Thread a=new Thread(runabble,"A");                
				 a.start();
				 Thread b=new Thread(runabble2,"B");
				 b.start();

      }
			}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?