sychronized
- package com.xiaozhi.threadlocal2;
- public class Test {
- public static void main(String[] args) {
- MyRun myRun=new MyRun();
- for(int i=0;i<10;i++)
- new Thread(myRun).start();
- }
- }
- class MyRun implements Runnable {
- int num = 10;
- public synchronized void run() {
- while(num > 0) {
- try {Thread.sleep(1000);} catch (InterruptedException e) {}
- num--;
- System.out.println(num);
- }
- }
- }
lock
- package com.xiaozhi.threadlocal2;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Test {
- public static void main(String[] args) {
- MyRun myRun=new MyRun();
- for(int i=0;i<10;i++)
- new Thread(myRun).start();
- }
- }
- class MyRun implements Runnable {
- int num = 10;
- Lock lock = new ReentrantLock();
- public /*synchronized*/ void run() {
- lock.lock();
- try {
- while(num > 0) {
- try {Thread.sleep(1000);} catch (InterruptedException e) {}
- num--;
- System.out.println(num);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- lock.unlock();
- }
- }
- }