21xrx.com
2024-09-19 23:56:16 Thursday
登录
文章检索 我的文章 写文章
Java上机考试题及答案
2023-06-19 14:21:50 深夜i     --     --
Java 上机考试 单例模式 死锁 可变参数

在软件行业中,Java技术可以说是非常重要的一门技术。因此,在各大高校中,Java的考试也非常严谨,无论是上机考试还是笔试。以下是一组Java上机考试题及答案,供读者参考。

第一题:实现一个单例模式,请写出你的代码实现。(15分)

解:单例模式可以通过懒汉模式和饿汉模式两种方式进行。在此我们给出一个懒汉式的单例模式代码实现。

public class Singleton {

  private static Singleton instance;

  private Singleton (){}

  public static Singleton getInstance() {

   if (instance == null) {

     instance = new Singleton();

   }

   return instance;

  }

}

第二题:请写一个死锁的例子,并解释产生死锁的原因。(20分)

解:以下是一个死锁的例子。

public class DeadLockSample extends Thread {

  private String firstObj;

  private String secondObj;

  public DeadLockSample(String name, String firstObj, String secondObj) {

    super(name);

    this.firstObj = firstObj;

    this.secondObj = secondObj;

  }

  @Override

  public void run() {

    synchronized (firstObj) {

      System.out.println(this.getName() + " obtained: " + firstObj);

      try {

        Thread.sleep(1000);

        synchronized (secondObj) {

          System.out.println(this.getName() + " obtained: " + secondObj);

        }

      } catch (InterruptedException e)

        // do nothing

    }

  }

  public static void main(String[] args) {

    String obj1 = "obj1";

    String obj2 = "obj2";

    DeadLockSample thread1 = new DeadLockSample("Thread1", obj1, obj2);

    DeadLockSample thread2 = new DeadLockSample("Thread2", obj2, obj1);

    thread1.start();

    thread2.start();

  }

}

产生死锁的原因是两个线程互相持有对方需要的资源,并且又在等待对方释放自己需要的资源,导致两个线程都无法继续执行下去。

第三题:请写出Java中可变参数的使用方法。(10分)

解:在Java中,可变参数使用三个点(...)表示。下面是一个示例代码。

public static void showArgs(String... args) {

  for(String arg : args) {

   System.out.println(arg);

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复