java多线程之线程锁
MyThread.java:
1 class MyThread implements Runnable { 2 int i = 1; 3 4 public void run() { 5 // 线程锁,一个线程执行本处代码时,其他线程等待本线程执行完毕后再执行; 6 // 如果不加线程锁,则线程会得到同一个数; 7 synchronized (this) { 8 if (i <= 0) { 9 return; 10 } 11 System.out.println(Thread.currentThread().getName() + "--->" + i); 12 i--; 13 } 14 } 15 }
TestMyThread.java:
1 class TestMyThread{ 2 public static void main(String[] args){ 3 MyThread myThread = new MyThread(); 4 Thread t1 = new Thread(myThread); 5 Thread t2 = new Thread(myThread); 6 Thread t3 = new Thread(myThread); 7 Thread t4 = new Thread(myThread); 8 t1.setName("线程1"); 9 t2.setName("线程2"); 10 t3.setName("线程3"); 11 t4.setName("线程4"); 12 t1.start(); 13 t2.start(); 14 t3.start(); 15 t4.start(); 16 try{ 17 Thread.sleep(1000); 18 }catch(Exception e){ 19 e.printStackTrace(); 20 } 21 System.out.println(myThread.i);//加锁时为0,不加锁为0到-3
22 } 23 }