并发得面试问题实战

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()); // 第三步获取结果
	}
}
发布了308 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_28764557/article/details/104457057