Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

5. Write a statement that causes the current thread to pause for at least 5 seco

ID: 3575044 • Letter: 5

Question

5.   Write a statement that causes the current thread to pause for at least 5 seconds.

     6.   Given a class named MonitorThread that extends the Thread class, write code to create an instance of this thread, set its priority to the lowest possible setting, and start the thread.

     7.   Write the code for a class named TickThread that extends the Thread class. The run method for this class should display the message “Tick” on the console at approximately one second intervals until the thread is interrupted. The method should use both isInterrupted() and InterruptedException to find out if it has been interrupted.

     8.   Write the main method for an application that creates and starts a thread named from a class named TickThread (assume this class extends Thread), pauses for five seconds, then interrupts the TickThread thread.

     9.   Write the code for a public class named SequenceNumber that has a single method named getSequenceNumber. This method should return an integer value that increases by 1 each time the method is called. The first time the method is called, it should return 1. The method should be written so that it can safely be called by multiple threads.

   10.   Write a while loop that causes the current thread to wait until a class variable named accountBalance has a value that’s greater than zero.

Explanation / Answer


5. int milliseconds = 2000;
   Thread.Sleep(milliseconds)

6.public class ThreadExample {
public static void main(String[] args){
    System.out.println(Thread.currentThread().getName());
    for(int i=0; i<10; i++){
      new Thread("" + i){
        public void run(){
          System.out.println("Thread: " + getName() + " running");
        }
      }.start();
    }
}
}


7. public abstract class SecondCountDownTimer {
private final int seconds;
private TimerThread timer;
private final Handler handler;
public SecondCountDownTimer(int secondsToCountDown) {
    seconds = secondsToCountDown;
    handler = new Handler();
    timer = new TimerThread(secondsToCountDown);
}
public SecondCountDownTimer start(int secondsToCountDown) {
    if (timer.getState() != State.NEW) {
        timer.interrupt();
        timer = new TimerThread(secondsToCountDown);
    }
    timer.start();
    return this;
}
/** This will cancel your current timer and start a new one. **/
public SecondCountDownTimer start() {
    return start(seconds);
}
public void cancel() {
    if (timer.isAlive()) timer.interrupt();
    timer = new TimerThread(seconds);
}
public abstract void onTick(int secondsUntilFinished);
private Runnable getOnTickRunnable(final int second) {
    return new Runnable() {
        @Override
        public void run() {
            onTick(second);
        }
    };
}
public abstract void onFinish();
private Runnable getFinishedRunnable() {
    return new Runnable() {
        @Override
        public void run() {
            onFinish();
        }
    };
}
private class TimerThread extends Thread {
    private int count;
    private TimerThread(int count) {
        this.count = count;
    }
    @Override
    public void run() {
        try {
            while (count != 0) {
                handler.post(getOnTickRunnable(count--));
                sleep(1000);
            }
        } catch (InterruptedException e) { }
        if (!isInterrupted()) {
            handler.post(getFinishedRunnable());
        }
    }
}



8. class TestSleepMethod1 extends Thread{  
public void run(){  
  for(int i=1;i<5;i++){  
    try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
    System.out.println(i);  
  }  
}  
public static void main(String args[]){  
  TestSleepMethod1 t1=new TestSleepMethod1();  
  TestSleepMethod1 t2=new TestSleepMethod1();  
   
  t1.start();  
  t2.start();  
}  
}  

9. import java.lang.ref.SoftReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.prefs.Preferences;
public final class SequenceNumber {
    private static final Preferences PREFS = Preferences.userNodeForPackage(SequenceNumber.class);
    private static final AtomicLong SEQ_ID = new AtomicLong(Integer.parseInt(PREFS.get("seq_id", "1")));
    private static final Map<Long, SoftReference<SequenceNumber>> GENERATORS = new ConcurrentHashMap<>();
    private static final SequenceNumber DEF_GENERATOR = new SequenceNumber(0L, Long.parseLong(PREFS.get("seq_0", "1")));
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            GENERATORS.values().stream()
                    .map(SoftReference::get)
                    .filter(seq -> seq != null && seq.isPersistOnExit())
                    .forEach(SequenceNumber::persist);
            if (DEF_GENERATOR.isPersistOnExit()) {
                DEF_GENERATOR.persist();
            }
            PREFS.put("seq_id", SEQ_ID.toString());
        }));
    }
    private final long sequenceId;
    private final AtomicLong counter;
    private final AtomicBoolean persistOnExit = new AtomicBoolean();
    private SequenceNumber(long sequenceId, long initialValue) {
        this.sequenceId = sequenceId;
        counter = new AtomicLong(initialValue);
    }
    public long nextId() {
        return counter.getAndIncrement();
    }
    public long currentId() {
        return counter.get();
    }
    public long getSequenceId() {
        return sequenceId;
    }
    public boolean isPersistOnExit() {
        return persistOnExit.get();
    }
    public void setPersistOnExit(boolean persistOnExit) {
        this.persistOnExit.set(persistOnExit);
    }
    public void persist() {
        PREFS.put("seq_" + sequenceId, counter.toString());
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        GENERATORS.remove(sequenceId);
        if (persistOnExit.get()) {
            persist();
        }
    }
    @Override
    public int hashCode() {
        return Long.hashCode(sequenceId);
    }
    @Override
    public boolean equals(Object obj) {
        return obj == this || obj != null && obj instanceof SequenceNumber && sequenceId == ((SequenceNumber) obj).sequenceId;
    }
    @Override
    public String toString() {
        return "{" +
                "counter=" + counter +
                ", seq=" + sequenceId +
                '}';
    }
    public static SequenceNumber getDefault() {
        return DEF_GENERATOR;
    }
    public static SequenceNumber get(long sequenceId) {
        if (sequenceId < 0) {
            throw new IllegalArgumentException("(sequenceId = " + sequenceId + ") < 0");
        }
        if (sequenceId == 0) {
            return DEF_GENERATOR;
        }
        SoftReference<SequenceNumber> r = GENERATORS.computeIfAbsent(sequenceId, sid -> {
            try {
                return new SoftReference<>(new SequenceNumber(sid, Long.parseLong(PREFS.get("seq_" + sid, null))));
            } catch (Throwable t) {
                return null;
            }
        });
        return r == null ? null : r.get();
    }
    public static SequenceNumber create() {
        return create(1);
    }
    public static SequenceNumber create(long initialValue) {
        long sequenceId = SEQ_ID.getAndIncrement();
        SequenceNumber seq = new SequenceNumber(sequenceId, Long.parseLong(PREFS.get("seq_" + sequenceId, "" + initialValue)));
        GENERATORS.put(sequenceId, new SoftReference<>(seq));
        return seq;
    }
}


10. import java.util.Scanner;
public class InterestCalculator
{
    public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
   Scanner input = new Scanner(System.in);
   int quartersDisplayed;
   double b, IR;
    do
{
     Scanner keyboard=new Scanner(System.in);
     System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
     quartersDisplayed = keyboard.nextInt();
     System.out.println("Next enter the starting balance. ");
     System.out.println("This input must be greater than zero: ");
     b = keyboard.nextDouble();
     System.out.println("Finally, enter the interest rate ");
     System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
     IR = keyboard.nextDouble();
     System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);         
     System.out.println("You also entered the starting balance of: " + b);
     System.out.println("Finally, you entered the following of interest rate: " + IR);
     System.out.println("If this information is not correct, please exit the program and enter the correct information.");
     double quarterlyEndingBalance = b + (b * IR/100 * .25);
     System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);  
     System.out.println("Do you want to continue?");
     String yes=keyboard.next("yes");
     if (yes.equals(yes))
     continue;
     else
     break;
        }
        while(true);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote