并发得面试问题实战

27 篇文章 0 订阅
14 篇文章 0 订阅
本文详细介绍了多线程技术的应用,包括通过synchronized关键字和ReentrantLock实现线程间的同步与通信,以及使用CountDownLatch进行线程间的等待通知机制。此外,还深入探讨了ForkJoin框架在解决大规模并行计算问题上的应用,如计算大量数据的累积求和。
摘要由CSDN通过智能技术生成

1.不断得打印123 123 123:代码yzy得ta8,注意先搭架子再说别的。

注意这个架子是必须得。

注意不能在加锁得方法里面while true得这样就永远就解不开锁了。

用wait和notify的模板的:

package thread.ta8;

public class DemoMy {

    
    public synchronized void a(){
        System.out.println("1");
    }

    public synchronized void b(){
        System.out.println("2");
    }

    public synchronized void c(){
        System.out.println("3");
    }

    public static void main(String[] args) {
        DemoMy demo = new DemoMy();
        AA a = new AA(demo);
        BB b = new BB(demo);
        CC c = new CC(demo);
        new Thread(a).start();
        new Thread(b).start();
        new Thread(c).start();
    }
}

// 三个线程所以我们要设计三个runnbale

class AA implements Runnable{
    private DemoMy demo;
    public AA(DemoMy demo) {
        this.demo = demo;
    }
    @Override
    public void run(){
        while(true){
            demo.a();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class BB implements Runnable{
    private DemoMy demo;
    public BB(DemoMy demo) {
        this.demo = demo;
    }
    @Override
    public void run(){
        while(true){
            demo.b();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class CC implements Runnable{
    private DemoMy demo;
    public CC(DemoMy demo) {
        this.demo = demo;
    }
    @Override
    public void run(){
        while(true){
            demo.c();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

用Reentrantlock的模板的:

package thread.ta9;

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

public class DemoMy {
    private int signal;
    private Lock lock = new ReentrantLock();
    Condition a = lock.newCondition();
    Condition b = lock.newCondition();
    Condition c = lock.newCondition();

    public void a(){
       lock.lock();
        while(signal!=0){
            try {
                a.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        signal = signal+1;
        System.out.println(signal);
        b.signal(); // 叫醒b
        lock.unlock();
    }

    public void b(){
        lock.lock();
        lock.unlock();
    }

    public void c(){
        lock.lock();
        lock.unlock();
    }

    public static void main(String[] args) {
        DemoMy demo = new DemoMy();
        AA a = new AA(demo);
        BB b = new BB(demo);
        CC c = new CC(demo);
        new Thread(a).start();
        new Thread(b).start();
        new Thread(c).start();
    }
}

class AA implements Runnable{
    private DemoMy demo;
    public AA(DemoMy demo) {
        this.demo = demo;
    }
    @Override
    public void run(){
        while(true){
            demo.a();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class BB implements Runnable{
    private DemoMy demo;
    public BB(DemoMy demo) {
        this.demo = demo;
    }
    @Override
    public void run(){
        while(true){
            demo.b();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class CC implements Runnable{
    private DemoMy demo;
    public CC(DemoMy demo) {
        this.demo = demo;
    }
    @Override
    public void run(){
        while(true){
            demo.c();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2.使用多线程完成累计求和 tb4

package thread.tb4;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class Demo2 {
	private int[] nums;
	public Demo2(int line) {
		nums = new int[line];
	}
	public void calc(String line, int index, CountDownLatch latch) {
		String[] nus = line.split(",");
		int total = 0;
		for (String num : nus) {
			total += Integer.parseInt(num);
		}
		nums[index] = total;
		System.out.println(Thread.currentThread().getName() + " do work... " + line + " result:" + total);


		latch.countDown();  // 第二步


	}
	public void sum() {
		System.out.println("add total begin... ");
		int total = 0;
		for (int i = 0; i < nums.length; i++) {
			total += nums[i];
		}
		System.out.println("final:" + total);
	}
	public static void main(String[] args) {
		List<String> contents = readFile();
		int lineCount = contents.size();

		CountDownLatch latch = new CountDownLatch(lineCount);  //  第一步


		Demo2 d = new Demo2(lineCount);
		for (int i = 0; i < lineCount; i++) {
			final int j = i;
			new Thread(new Runnable() {
				@Override
				public void run() {
					d.calc(contents.get(j), j, latch);
				}
			}).start();
		}


		try {
			latch.await();// 第三步
		} catch (InterruptedException e) {
			e.printStackTrace();
		}


		d.sum();
	}
	private static List<String> readFile() {
		List<String> contents = new ArrayList<>();
		String line = null;
		BufferedReader br = null;
		try {
			//br = new BufferedReader(new FileReader("e:\\nums.txt"));
			br = new BufferedReader(new FileReader("D:\\CODE_My\\threadyzy\\src\\main\\java\\thread\\tb4\\nums.txt"));
			while ((line = br.readLine()) != null) {
				contents.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return contents;
	}
}

3.求1+2+3+4+5+6+..........................一直加到100的值。 ForkJoin框架。

package thread.tc1;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class Demo extends RecursiveTask<Integer> {
	private int begin;
	private int end;
	public Demo(int begin, int end) {
		this.begin = begin;
		this.end = end;
	}
	@Override
	protected Integer compute() {
		System.out.println(Thread.currentThread().getName() + " ... ");
		int sum = 0;
		// 拆分任务
		if (end - begin <= 2) {//两个数或者三个数
			// 计算
			for (int i = begin; i <= end; i++) {
				sum += i;
			}
		} else {
			// 拆分
			Demo d1 = new Demo(begin, (begin + end) / 2);//任务折半 搞很多的RecursiveTask 再创建任务
			Demo d2 = new Demo((begin + end)/2 + 1, end);
			// 执行任务 依然拿到的是订单
			d1.fork();
			d2.fork();
			Integer a = d1.join(); // 合并就的值
			Integer b = d2.join();
			sum = a + b;
		}
		return sum;
	}
	public static void main(String[] args) throws Exception {
		ForkJoinPool pool = new ForkJoinPool(5);// 第一步
		Future<Integer> future = pool.submit(new Demo(1, 10000));// 第二步提交任务
		System.out.println("....");
		System.out.println("计算的值为:" + future.get()); // 第三步获取结果
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值