Java Thread 锁Synchronized (一)

Java线程中若是给方法加锁,有一些陷井。下面用些例子进行详解ide

先构建一个Task类有两个执行方法测试

class Task {
    public void excute1(String threadName) {
        for (int i = 0; i <= 20; i++) {
            System.out.println(threadName + " ------ " + i);
        }
    }
    public void excute2(String threadName){
        for (int i = 0; i <= 20; i++) {
            System.out.println(threadName + " ------ " + i);
        }
    }
}

两个线程来分别调用Task中的excute1,excute2方法this

ThreadA线程

class ThreadA extends Thread {
    private Task task;
    public ThreadA(Task task) {
        this.task = task;
    }
    @Override
    public void run() {
        task.excute1(this.getName());
    }
}

ThreadBcode

class ThreadB extends Thread {
    private Task task;
    public ThreadB(Task task) {
        this.task = task;
    }
    @Override
    public void run() {
        task.excute2(this.getName());
    }
}

用一个测试类进行测试对象

public class SychronizeTest {
    public static void main(String[] args) {
        Task t = new Task();
        ThreadA ta = new ThreadA(t);
        ThreadB tb = new ThreadB(t);
        ta.start();
        tb.start();
    }
}

这时候测试,代码执行结果会两个线程错乱。。。,若是想有序执行,就须要加入Sychronized 关键字到excute1 和 excute2上。get

class Task {
    public synchronized void excute1(String threadName) {
        for (int i = 0; i <= 20; i++) {
            System.out.println(threadName + " ------ " + i);
        }
    }
    public synchronized  void excute2(String threadName){
        for (int i = 0; i <= 20; i++) {
            System.out.println(threadName + " ------ " + i);
        }
    }
}

虽然说两个线程执行不一样的方法,可是结果仍是会有序的执行,缘由是当访问某个对象的Synchronized方法时,表示将对该对象上锁,此时其它任何线程都没法访问该对象下的synchronized方法,直接该对象把锁释放掉,其它线程才能够访问class

相关文章
相关标签/搜索