Java同步代码块和同步方法处理Thread类和Runnable的线程安全问题

Java同步代码块和同步方法处理Thread类和Runnable的线程安全问题

源出处:http://www.gulixueyuan.com/my/course/310

例子:创建三个窗口卖票,总票数为100张

  1. 问题:卖票过程中,出现了重票、错票 -->出现了线程的安全问题
  2. 问题出现的原因:当某个线程操作车票的过程中,操作尚未完成时,其他线程参与进来,也操作车票。
  3. 如何解决:当一个线程a在操作ticket的时候,其他线程不能参与进来。直到线程a操作完ticket时,其他线程才可以开始操作ticket。这种情况即使线程a出现了阻塞,也不能被改变。
  4. 在Java中,我们可以通过同步机制,来解决线程的安全问题。

方式一:同步代码块

synchronized(同步监视器){
	//需要被同步的代码
}
使用同步代码块解决继承Thread类的方式的线程安全问题:
/**
 * 例子:创建三个窗口卖票,总票数为100张,使用继承Thread类的方式
 *
 * 说明:在继承Thread类创建多线程的方式中,慎用this充当同步监视器,考虑使用当前类充当同步监视器
 */
class Window2 extends Thread{

    private static int ticket = 100;   //100张票

    private static Object object = new Object();

    @Override
    public void run() {
        while (true){
            //synchronized (object){
            synchronized (Window2.class){
                //错误的方式:synchronized (this){    this代表三个对象
                if (ticket>0){
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+":卖票,票号为:"+ticket);
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
}

public class WindowTest2 {
    public static void main(String[] args) {
        Window2 window1 = new Window2();
        Window2 window2 = new Window2();
        Window2 window3 = new Window2();

        window1.setName("窗口1");
        window2.setName("窗口2");
        window3.setName("窗口3");

        window1.start();
        window2.start();
        window3.start();
    }
}

使用同步代码块解决实现Runnable接口方式的线程安全问题:
//创建一个实现了Runnable接口的类
class Window1 implements Runnable{

    private int ticket = 100;   //100张票
    //Object object = new Object();
    Dog dog = new Dog();

    //实现类去实现Runnable中的抽象方法:run()
    @Override
    public void run() {
        while (true){
            synchronized(this){ //此时的this:唯一的window1的对象    //方式二:synchronized(dog) {
                if (ticket > 0) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "号窗口:卖票,票号为:" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}

public class WindowTest1 {
    public static void main(String[] args) {
        //创建实现类的对象
        Window1 window1 = new Window1();

        //将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread thread1 = new Thread(window1);
        Thread thread2 = new Thread(window1);
        Thread thread3 = new Thread(window1);

        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");

        //通过Thread类的对象调用start():①启动线程 ②调用当前线程的run()
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

class Dog{

}

方式二:同步方法

关于同步方法的总结:

  1. 同步方法仍然涉及到同步监视器,只是不需要我们显式的声明。
  2. 非静态的同步方法,同步监视器是:this
    静态的同步方法,同步监视器是:当前类本身
使用同步方法处理继承Thread类的方式中的线程安全问题
class Window4 extends Thread {

    private static int ticket = 100;   //100张票

    private static Object object = new Object();

    @Override
    public void run() {
        while (true) {
            show();
        }
    }

    private static synchronized  void show(){
    //private synchronized void show(){   //同步监视器:window1、window2、window3
        if (ticket>0){
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":卖票,票号为:"+ticket);
            ticket--;
        }
    }
}

public class WindowTest4 {
    public static void main(String[] args) {
        Window4 window1 = new Window4();
        Window4 window2 = new Window4();
        Window4 window3 = new Window4();

        window1.setName("窗口1");
        window2.setName("窗口2");
        window3.setName("窗口3");

        window1.start();
        window2.start();
        window3.start();
    }
}
使用同步方法解决实现Runnable接口的线程安全问题
class Window3 implements Runnable{

    private int ticket = 100;   //100张票

    //实现类去实现Runnable中的抽象方法:run()
    @Override
    public void run() {
        while (true){
            show();
        }
    }

    private synchronized void show(){   //同步监视器:this
        //synchronized (this){
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "号窗口:卖票,票号为:" + ticket);
            ticket--;
        }
    }

}

public class WindowTest3 {
    public static void main(String[] args) {
        //创建实现类的对象
        Window3 window = new Window3();

        //将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread thread1 = new Thread(window);
        Thread thread2 = new Thread(window);
        Thread thread3 = new Thread(window);

        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");

        //通过Thread类的对象调用start():①启动线程 ②调用当前线程的run()
        thread1.start();
        thread2.start();
        thread3.start();

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java线程模拟生产者/消费者问题的示例代码,其中使用了同步方法来解决可能出现的死锁问题: ``` public class ProducerConsumerExample { private static Queue<Integer> buffer = new LinkedList<>(); private static final int BUFFER_SIZE = 10; public static void main(String[] args) throws InterruptedException { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); producerThread.join(); consumerThread.join(); } static class Producer implements Runnable { @Override public void run() { for (int i = 0; i < 50; i++) { try { produce(i); } catch (InterruptedException e) { e.printStackTrace(); } } } private void produce(int i) throws InterruptedException { synchronized (buffer) { while (buffer.size() == BUFFER_SIZE) { System.out.println("Buffer is full. Waiting for consumer to consume."); buffer.wait(); } buffer.add(i); System.out.println("Produced " + i); buffer.notifyAll(); } } } static class Consumer implements Runnable { @Override public void run() { while (true) { try { consume(); } catch (InterruptedException e) { e.printStackTrace(); } } } private void consume() throws InterruptedException { synchronized (buffer) { while (buffer.isEmpty()) { System.out.println("Buffer is empty. Waiting for producer to produce."); buffer.wait(); } int value = buffer.poll(); System.out.println("Consumed " + value); buffer.notifyAll(); } } } } ``` 在这个示例代码中,我们定义了一个缓冲区 `buffer`,使用 `LinkedList` 来实现队列的功能。我们通过两个内部类 `Producer` 和 `Consumer` 来分别模拟生产者和消费者线程。在 `Producer` 内部,我们使用 `synchronized` 关键字来保证在多线程环境下对 `buffer` 的访问是互斥的。当 `buffer` 已满时,生产者线程将等待消费者线程消费一部分数据之后再继续生产。在 `Consumer` 内部同样使用 `synchronized` 关键字来保证对 `buffer` 的访问是互斥的。当 `buffer` 为空时,消费者线程将等待生产者线程生成一些新的数据。 注意,在使用 `wait()` 和 `notifyAll()` 方法时,必须在同步块中调用,否则会抛出 `IllegalMonitorStateException` 异常。 通过这种方式,我们可以保证生产者和消费者线程之间的同步,避免了死锁问题的发生。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值