Java多线程_对象及其变量的并发访问(2)

静态同步synchronized方法与synchronized(class)代码块

synchronized天键子加到static静态方法上是给Class类上锁,而 synchronized关键字加到非 static静态方法上是给对象上锁。

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        Service service = new Service();
        //同一个类,同一个对象
        ThreadA aThread = new ThreadA(service);
        ThreadB bThread = new ThreadB(service);
        ThreadC cThread = new ThreadC(service);
        aThread.setName("A");
        bThread.setName("B");
        cThread.setName("C");
        aThread.start();
        bThread.start();
        cThread.start();

    }
}
package multiply.com.test;
public class ThreadA extends Thread {
    private Service service;

    public ThreadA(Service service) {
        this.service = service;
    }
    @Override
    public void run() {
        super.run();
        service.printA();
    }
}
package multiply.com.test;
public class ThreadB  extends Thread {
    private Service service;
    public ThreadB(Service service) {
        this.service = service;
    }
    @Override
    public void run() {
        super.run();
        service.printB();
    }
}
package multiply.com.test;
public class ThreadC extends Thread {
    private Service service;
    public ThreadC(Service service) {
        this.service = service;
    }
    @Override
    public void run() {
        super.run();
        service.printC();
    }
}
package multiply.com.test;
public class Service {
    synchronized public static void printA() {
        try {
            System.out.println("thread name = " + Thread.currentThread().getName() + " in printA at " + System.currentTimeMillis());
            Thread.sleep(3000);
            System.out.println("thread name = " + Thread.currentThread().getName() + " out printA at " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    synchronized public static void printB() {
        System.out.println("thread name = " + Thread.currentThread().getName() + " in printB at " + System.currentTimeMillis());
        System.out.println("thread name = " + Thread.currentThread().getName() + " out printB at " + System.currentTimeMillis());
    }
    synchronized public void printC() {
        System.out.println("thread name = " + Thread.currentThread().getName() + " in printC at " + System.currentTimeMillis());
        System.out.println("thread name = " + Thread.currentThread().getName() + " out printC at " + System.currentTimeMillis());
    }
}

thread name = C in printC at 1634869837541
thread name = A in printA at 1634869837541
thread name = C out printC at 1634869837541
thread name = A out printA at 1634869840542
thread name = B in printB at 1634869840542
thread name = B out printB at 1634869840542

A和B是类锁,是并行的。C是对象锁是和A串行的。

数据类型String的常量池特性

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
    	//不同对象
        ThreadA aThread = new ThreadA();
        ThreadB bThread = new ThreadB();
        aThread.setName("A");
        bThread.setName("B");
        aThread.start();
        bThread.start();
    }
}
package multiply.com.test;
public class ThreadA extends Thread {
    @Override
    public void run() {
        super.run();
        Service.print("AA");
    }
}
package multiply.com.test;
public class ThreadB extends Thread {
    @Override
    public void run() {
        super.run();
        Service.print("AA");
    }
}
package multiply.com.test;
public class Service {
    public static void print(String stringParam) {
        try {
            synchronized (stringParam) {
                while (true) {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(1000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

B
B
B
B…
出现这样的情况就是因为String 的两个值都是AA,两个线程持有相同的锁。synchronized代码块都不使用String作为锁对象,而改用其他,比如new Object()实例化一个Object对象,但它并不放入缓存中。

多线程的死锁

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        try {
            DealThread t1 = new DealThread();
            t1.setFlag("a");
            Thread thread1 = new Thread(t1);
            thread1.start();
            Thread.sleep(100);
            t1.setFlag("b");
            Thread thread2 = new Thread(t1);
            thread2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class DealThread implements Runnable {
    public String username;
    public Object lock1 = new Object();
    public Object lock2 = new Object();
    public void setFlag(String username) {
        this.username = username;
    }
    @Override
    public void run() {
        if ("a".equals(username)) {
            synchronized (lock1) {
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (lock2) {
                    System.out.println("lock1 -> lock2");
                }
            }
        }
        if ("b".equals(username)) {
            synchronized (lock2) {
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("lock2 -> lock1");
                }
            }
        }

    }
}
内置类与静态内置类

在内置类中有两个同步方法,但使用的却是不同的锁,打印的结果也是异步的。

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
    	//对象是同一个
        final OutClass.Inner inner = new OutClass.Inner();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                inner.method1();
            }
        }, "A");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                inner.method2();
            }
        }, "B");
        t1.start();
        t2.start();
    }
}
package multiply.com.test;
public class OutClass {
    static class Inner {
        public void method1() {
            synchronized ("其他的锁") {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + " i = " + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public synchronized void method2() {
            for (int i = 11; i < 20; i++) {
                System.out.println(Thread.currentThread().getName() + " i = " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述

volatile关键字

关键字 volatile的主要作用是使变量在多个线程间可见。

解决同步死循环

package multiply.com.test;
public class Run {
    public static void main(String[] args) throws InterruptedException {
        PrintString printStringService = new PrintString();
        new Thread(printStringService).start();
        System.out.println("I want to stop it ! stop thread = " + Thread.currentThread().getName());
        printStringService.setContinuePrint(false);
    }
}
package multiply.com.test;
public class PrintString implements Runnable {
    private boolean isContinuePrint = true;
    public boolean isContinuePrint() {
        return isContinuePrint;
    }
    public void setContinuePrint(boolean isContinuePrint) {
        this.isContinuePrint = isContinuePrint;
    }
    public void printStringMethod() {
        try {
            while (isContinuePrint == true) {
                System.out.println("run printStringMethod thread name = " + Thread.currentThread().getName());
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        printStringMethod();
    }
}

I want to stop it ! stop thread = main
run printStringMethod thread name = Thread-0

关键字volatile的作用是强制从公共堆栈中取得变量的值,而不是从线程私有数据栈中取得变量的值。

在启动Run Thread.java线程时,变量private boolean isRunning = true;存在于公共堆栈及线程的私有堆栈中。在JVM被设置为-server模式时为了线程运行的效率,线程一直在私有堆栈中取得 isRunning 的值是true。而代码thread.setRunning(false);虽然被执行,更新的却是公共堆栈中的 isRunning 变量值false,所以一直就是死循环的状态。内存结构如图2-75所示。

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        try {
            RunThread thread = new RunThread();
            thread.start();
            Thread.sleep(1000);
            thread.setRunning(false);
            System.out.println("isRunning is set by false");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class RunThread extends Thread {
    volatile private boolean isRunning = true;
    public boolean isRunning() {
        return isRunning;
    }
    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }
    @Override
    public void run() {
        super.run();
        System.out.println("in run method ");
        while (isRunning == true) {

        }
        System.out.println("end run method");
    }
}

in run method
isRunning is set by false
end run method

下面将关键字synchronized和 volatile进行一下比较:

  • 关键字volatile是线程同步的轻量级实现,所以volatile性能肯定比synchronized要好,并且volatile只能修饰于变量,而synchronized可以修饰方法,以及代码块
  • 多线程访问volatile不会发生阻塞,而synchronized会出现阻塞。
  • volatile能保证数据的可见性,但不能保证原子性;而synchronized可以保证原子性,也可以间接保证可见性,因为它会将私有内存和公共内存中的数据做同步。此知识点在后面。
  • 关键字volatile解决的是变量在多个线程之间的可见性;而 synchronized关键字解决的是多个线程之间访问资源的同步性

synchronized代码块具有volatile数据同步功能

关键字synchronized可以使多个线程访问同一个资源具有同步性,而且它还具有将线程工作内存中的私有变量与公共内存中的变量同步的功能,在此实验中进行验证。

package multiply.com.test;
public class Run {
    public static void main(String[] args) throws InterruptedException {
        Service service = new Service();
        ThreadA a = new ThreadA(service);
        a.start();
        Thread.sleep(1000);
        ThreadB b = new ThreadB(service);
        b.start();
        System.out.println("had been stopped !");
    }
}
package multiply.com.test;
public class ThreadA extends Thread{
    private Service service;

    public ThreadA(Service service) {
        this.service = service;
    }
    @Override
    public void run() {
        super.run();
        service.runMethod();
    }
}
package multiply.com.test;
public class ThreadB extends Thread {
    Service service;

    public ThreadB(Service service) {
        this.service = service;
    }
    @Override
    public void run() {
        super.run();
        service.stopMethod();
    }
}
package multiply.com.test;
public class Service {
    private boolean isContinueRun = true;
    synchronized public void runMethod() {
        String anyString = new String();
        while (true == isContinueRun) {
            synchronized (anyString) {
            }
        }
        System.out.println("stopped!");
    }

    public void stopMethod() {
        isContinueRun = false;
    }
}

had been stopped !
stopped!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

身影王座

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值