多线程基础面试题

文章展示了使用Java实现多线程的三个场景:一是电脑生产与搬运的同步控制,确保生产一台搬运一台;二是通过标志变量实现加减法操作的线程同步,防止数据冲突;三是模拟竞拍过程,只有一个线程能成功抢答。每个示例都用到了`synchronized`关键字和`wait/notify`机制来协调线程间的协作。
摘要由CSDN通过智能技术生成

生产搬运电脑

/**
 * 电脑生产与消费
 * 要求生产一台电脑搬运一台,
 * 若没生产出来,搬运等待
 * 若未搬运,等待生产,并计数
 */
class Resource1 {
    private int number = 0;//计数
    private Computer computer;//描述电脑资源

    public Resource1() {
        Thread numberDaemonThread = new Thread(() -> {
            while (true){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("【守护线程】电脑数量:" + this.number);
            }
        });
        numberDaemonThread.setDaemon(true);
        numberDaemonThread.start();
    }

    public synchronized void create(String brand, double price) {
        if (this.computer != null) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.computer = new Computer(brand, price);
        this.number++;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("【" + Thread.currentThread().getName() + "】电脑生产完成" + this.number);
        super.notify();
    }

    public synchronized void carry(String brand, double price) {
        if (this.computer == null) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("【" + Thread.currentThread().getName() + "】搬运电脑" + this.number);
        this.computer = null;
        super.notify();
    }
}

class Computer {
    private String brand;
    private double price;

    public Computer(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Computer{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

public class Test02 {
    public static void main(String[] args) {
        Resource1 resource1 = new Resource1();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                resource1.create("外星人",2999.01);
            }
        },"电脑生产线程").start();
        new Thread(()->{
            for (int j = 0; j < 10; j++) {
                resource1.carry("外星人",2999.01);
            }
        },"电脑搬运线程").start();
    }
}

多线程进行加减法

/**
 * 设4各线程对象,2个用来加操作,2个用来减操作
 */
class Resource {
    private int number = 0;//操作的数字
    /**
     * 加减法标志:
     * flag=true :表示可以进行加法操作,不可以减法
     * flag=false :表示可以进行减法操作,不可以加法
     */
    private boolean flag;
    public synchronized void add(){
        while (flag == false){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.number++;//加法操作
        System.out.println("[" + Thread.currentThread().getName() + "]执行加法操作结果为:" + this.number);
        this.flag = false;
        super.notifyAll();  //为防止某些线程为唤醒
    }
    public synchronized void sub(){
        while (this.flag == true){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.number--;
        System.out.println("[" + Thread.currentThread().getName() + "]执行减法操作结果为:" + this.number);
        this.flag = true;
        super.notifyAll();
    }

}

public class Test01 {
    public static void main(String[] args) throws Exception {
        Resource resource = new Resource();
        for (int i = 0; i < 2; i++) {//加法线程
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    synchronized (resource){
                        resource.add();
                    }
                }
            },"{加法线程} i=" + i).start();
        }
        for (int i = 0; i < 2; i++) {//加法线程
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    synchronized (resource){
                        resource.add();
                    }
                }
            },"{减法线程} i=" + i).start();
        }
    }
}

多线程——竞拍抢答

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 竞拍抢答:设置3各抢答者,发出命令后,给抢答者发出抢答结果
 */
class AnswerThread implements Callable<String> {

    private boolean flag;//抢答结果

    @Override
    public String call() throws Exception {

        if (this.flag == false) {
            this.flag = true;//设置抢答标志
            return "【" + Thread.currentThread().getName() + "】你抢答成功";
        }else {
            return "【" + Thread.currentThread().getName() + "】抢答失败";
        }
    }
}

public class Test01 {
    public static void main(String[] args) throws Exception {
        AnswerThread answerThread = new AnswerThread();
        FutureTask<String> futureTask1 = new FutureTask<>(answerThread);
        FutureTask<String> futureTask2 = new FutureTask<>(answerThread);
        FutureTask<String> futureTask3 = new FutureTask<>(answerThread);
        new Thread(futureTask1).start();
        new Thread(futureTask2).start();
        new Thread(futureTask3).start();
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
        System.out.println(futureTask3.get());
    }
}

----------------------
output:Thread-0】你抢答成功
【Thread-1】抢答失败
【Thread-2】抢答失败
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值