多线程(二)

JDK5—Lock 虽然我们可以理解同步代码块和同步方法的锁对象问题,但是我们并没有直接看到在哪里加上了锁,在哪里释放了锁, 为了更清晰的表达如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock。 Lock: void lock(): 获取锁。 void unlock():释放锁。 ReentrantLock是Lock的实现类。package
摘要由CSDN通过智能技术生成

JDK5—Lock

  虽然我们可以理解同步代码块和同步方法的锁对象问题,但是我们并没有直接看到在哪里加上了锁,在哪里释放了锁,
  为了更清晰的表达如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock。

  Lock:
        void lock(): 获取锁。
        void unlock():释放锁。  
  ReentrantLock是Lock的实现类。
package cn.itcast_01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
   

    // 定义票
    private int tickets = 100;

    // 定义锁对象
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                // 加锁
                lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()
                            + "正在出售第" + (tickets--) + "张票");
                }
            } finally {
                // 释放锁
                lock.unlock();
            }
        }
    }

}
package cn.itcast_01;

public class SellTicketDemo {
    public static void main(String[] args) {
        // 创建资源对象
        SellTicket st = new SellTicket();

        // 创建三个窗口
        Thread t1 = new Thread(st, "窗口1");
        Thread t2 = new Thread(st, "窗口2");
        Thread t3 = new Thread(st, "窗口3");

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

死锁问题

  同步的弊端:
        A:效率低
        B:容易产生死锁

  死锁:
        两个或两个以上的线程在争夺资源的过程中,发生的一种相互等待的现象。

  举例:
        中国人,美国人吃饭案例。
        正常情况:
            中国人:筷子两支
            美国人:刀和叉
        现在:
            中国人:筷子1支,刀一把
            美国人:筷子1支,叉一把
package cn.itcast_02;

public class MyLock {
   
    // 创建两把锁对象
    public static final Object objA = new Object();
    public static final Object objB = new Object();
}
package cn.itcast_02;

public class DieLock extends Thread {
   

    private boolean flag;

    public DieLock(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (MyLock.objA) {
                System.out.println("if objA");
                synchronized (MyLock.objB) {
                    System.out.println("if objB");
                }
            }
        } 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于您没有给出具体的问题或数据集,我无法为您提供完整的代码,但我可以给您提供一些思路和伪代码来实现多线程维卷积计算。 1. 定义卷积核和输入图像 ``` kernel = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]] # 3x3 Sobel filter image = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # 4x4 input image ``` 2. 定义卷积函数 ``` def convolve(kernel, image): # Get kernel and image dimensions kernel_height, kernel_width = len(kernel), len(kernel[0]) image_height, image_width = len(image), len(image[0]) # Initialize output image output = [[0 for _ in range(image_width - kernel_width + 1)] for _ in range(image_height - kernel_height + 1)] # Compute convolution for i in range(kernel_height): for j in range(kernel_width): for k in range(image_height - kernel_height + 1): for l in range(image_width - kernel_width + 1): output[k][l] += kernel[i][j] * image[k+i][l+j] return output ``` 这个函数实现了基本的维卷积计算,但是它是串行的。我们需要将其并行化以加快计算速度。 3. 定义多线程卷积函数 ``` import threading class ConvolutionThread(threading.Thread): def __init__(self, kernel, image, output, row_start, row_end): threading.Thread.__init__(self) self.kernel = kernel self.image = image self.output = output self.row_start = row_start self.row_end = row_end def run(self): # Get kernel and image dimensions kernel_height, kernel_width = len(self.kernel), len(self.kernel[0]) image_height, image_width = len(self.image), len(self.image[0]) # Compute convolution for i in range(kernel_height): for j in range(kernel_width): for k in range(self.row_start, self.row_end): for l in range(image_width - kernel_width + 1): self.output[k][l] += self.kernel[i][j] * self.image[k+i][l+j] def parallel_convolve(kernel, image, num_threads): # Get kernel and image dimensions kernel_height, kernel_width = len(kernel), len(kernel[0]) image_height, image_width = len(image), len(image[0]) # Initialize output image output = [[0 for _ in range(image_width - kernel_width + 1)] for _ in range(image_height - kernel_height + 1)] # Split image into rows for each thread rows_per_thread = (image_height - kernel_height + 1) // num_threads threads = [] for i in range(num_threads): row_start = i * rows_per_thread row_end = row_start + rows_per_thread if i == num_threads - 1: row_end = image_height - kernel_height + 1 thread = ConvolutionThread(kernel, image, output, row_start, row_end) threads.append(thread) # Start threads for thread in threads: thread.start() # Wait for threads to finish for thread in threads: thread.join() return output ``` 这个函数将输入图像分成多个线程处理。每个线程处理一组连续的行。将图像分成多个线程可以大大减少计算时间。 4. 调用多线程函数 ``` num_threads = 4 result = parallel_convolve(kernel, image, num_threads) ``` 这个例子中,我们将输入图像分成4个线程处理。您可以根据计算机的处理器核心数量来选择线程数,以达到最佳性能。 希望这些思路和伪代码能够帮助您实现多线程维卷积计算。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值