Java实验七

第一题

编写应用程序,设计 4 个线程对象,两个线程执行减操作,两个线程执行加操作。

public class Main {
    public static void main(String[] args) {
        Data data = new Data();
        Add add = new Add(data);
        Dec dec = new Dec(data);
        for (int i = 0; i < 2; i++) {
            new Thread(add, "线程A").start();
            new Thread(dec, "线程B").start();
        }
    }
}
class Data {
    private int num = 0;
    public synchronized void add(){
        System.out.println(Thread.currentThread().getName() + "对num加1,当前num=" + (++num));
    }
    public synchronized void dec(){
        System.out.println(Thread.currentThread().getName() + "对num减1,当前num=" + (--num));
    }
}
class Add implements Runnable{
    private Data data;
    Add(Data data){
        this.data= data;
    }
    public void run() {
        data.add();
    }
}
class Dec implements Runnable{
    private Data data;
    Dec(Data data){
        this.data= data;
    }
    public void run() {
        data.dec();
    }
}

在这里插入图片描述

第二题

设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,则搬运工要等待新电脑产出;如果生产出的电脑没有搬走,电脑搬走之后再生产,并统计出生产的电脑数量。

class Computer{
	private String name;
	private static int sum=1;
	boolean falg =true;
	public Computer(String name) {
		super();
		this.name = name;
	}
	public synchronized void set(){
		if(!falg){
			try{
				super.wait();
			}catch(InterruptedException e){
				e.printStackTrace();}
		}try{
		    Thread.sleep(1000);			
		}catch(InterruptedException e){
			e.printStackTrace();}		
		System.out.println("当前生产了"+this.name+",已经生产了"+sum+"  台电脑!");
		sum++;
		falg=false;
		super.notify();
	}
	public synchronized void get(){
		if(falg){
			try{
				super.wait();
			}catch(InterruptedException e){
				e.printStackTrace();}
		}try{
			Thread.sleep(1000);			
	}catch(InterruptedException e){
		e.printStackTrace();}
	System.out.println("搬走了"+this.name);
	falg=true;
	super.notify();
	 }
}
class com implements Runnable{
	public void run(){
		for(int i=1;i<10;i++){
			Computer c=new Computer("电脑  "+i);
			c.set();
			c.get();
		}
	}	
}
public class test {
	public static void main(String[] args) {
		com t=new com();
		new Thread(t).start();
	}
}    

在这里插入图片描述

第三题

死锁就是指两个或两个以上线程都在等待彼此先完成,造成了程序的停滞状态,若无外力作用,它们都将无法推进下去。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Re:从零开始的代码生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值