How to write getch() in NACHOS (Java)? - java

So I am learning to create my own SerialConsole in nachos (Java). I learned using Semaphore.P() and Semaphore.V() to wait for user input. Everything is going well until I tried to make a function like getch() in C's conio.h.
The problem is, whenever I called Semaphore.P(), even though the Semaphore.V() is called, it will always wait for Enter key to be pressed before it resume the program. I wanted the program to resume whenever I press a key.
Below is some code I tried.
Console.java
public class Console {
private SerialConsole console;
private Semaphore sem = new Semaphore(0);
private Runnable send, recv;
private char tempChar;
public Console() {
console = Machine.console();
send = new Runnable() {
#Override
public void run() {
sem.V();
}
};
recv = new Runnable() {
#Override
public void run() {
tempChar = (char) console.readByte();
sem.V();
}
};
console.setInterruptHandlers(recv, send);
}
public String nextLine() {
String result = "";
do {
sem.P();
if (tempChar != '\n') result += tempChar;
} while(tempChar != '\n');
return result;
}
public char getch() {
sem.P();
return tempChar;
}
}
Main.java
public class Main {
private Console console;
public Main() {
console = new Console();
char c = console.getch();
System.out.println(c);
}
}
Is there anything I have missed or is there any way to programmatically press Enter key or something?
PS: java.awt.Robot can't be used inside a nachos project.
Any help would be appreciated.

Related

Using an extended Thread trough two instances of it's class is causing skipping of values

I have the next sample I am trying to run, but sometimes it runs fine, another it is not exiting the loop. I can imagine only that for some reason values are skipping.
By skipping the values I mean the flags meant to notify the loop in the class Flasher to exit, which are brought from class engine, ass well the flags meant to notify the loop in class Engine from class Flasher.
This is how I understood it could run the best possible and simplest way, but what is going on?
Can you please help?
//Main class:
public class Flasher {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
engine en1 = new engine("ZaikoBaiko");
engine en2 = new engine("MiliVaninili");
en1.start();
en2.start();
int Terminator2 = 0;
while(!en1.Terminator||!en2.Terminator)
{
}
System.out.println(" owns the last word");
en1.roboCop = true;
en2.roboCop = true;
}
}
//Thread Class:
public class engine extends Thread
{
public String OB;
public boolean Terminator = true;
public boolean roboCop = false;
private Thread t;
engine(String name)
{
OB = name;
Terminator = false;
}
#Override
public void run()
{
int x = 0;
while(x<100)
{
System.out.println(x+":"+OB);
x++;
}
Terminator = true;
while(!roboCop){}
}
#Override
public void start()
{
if(t==null)
{
t = new Thread(this,OB);
t.start();
}
}
}
The JVM is caching your variables. You need to add volatile to your check variables (Terminator, roboCop). This will ensure that all threads write/read the newest value to/from main memory.
For a detailed explanation here is a similar question!

Java Multithreading two classes in main

I am very new to programming, and I am trying to write a Java program with the Timer and ChecksUserInput classes shown below. How do I get them to run at the same time in the main class?
I am also having issues with printing out the word length in ChecksUserInput.
main.java:
package application;
public class Main {
public static void main(String[] args) {
CreateBoard board = new CreateBoard();
board.run();
Timer timer = new Timer();
timer.run();
ChecksUserInput input = new ChecksUserInput();
input.run();
}
}
timer.java:
package application;
public class Timer {
private static void time() {
final int mili = 1000;
final int sec = 60;
final int oneMinute = (mili * sec);
System.out.println("Start 3 minute timer");
sleep(oneMinute * 2);
System.out.println("One minute remaining...");
sleep(oneMinute);
System.out.println("Time's up!");
}
private static void sleep(int sleepTime) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
time();
}
}
checksuserinput.java:
package application;
import java.util.*;
public class ChecksUserInput {
private static String UserInput() {
Scanner sc = new Scanner(System.in);
System.out.println("Begin entering words!");
String word = null;
for (int i = 0; i < 10000; i++) {
word = sc.nextLine();
}
return word;
}
private static int length(String word) {
int wordLength = word.length();
return wordLength;
}
public void run() {
String userWord = UserInput();
int wordLength = length(userWord);
System.out.println(wordLength);
}
}
The foundation of multi-threading in Java is the Thread class. The general structure for usage is:
Thread newProcess = new Thread(processToRun); //Create a thread which will execute the process
newProcess.setDaemon(true/false); //when false, the thread will keep the JVM alive beyond completion of 'main'
newProcess.start(); //Start processToRun in a new thread
To start several independent processes, this should be sufficient. For example, the following starts 10 threads each of which will print the index in the loop. At the end, the process sleeps for 5 milliseconds because the spawned threads are daemon. Removing this may cause the process to terminate before any messages are printed.
public static void main(String args[]) throws Exception
{
for(int i = 0; i < 10; i++) { int index = i; start(() -> System.out.println(index)); }
Thread.sleep(5);
}
public static void start(Runnable processToRun)
{
Thread newProcess = new Thread(processToRun);
newProcess.setDaemon(true);
newProcess.start();
}
Beyond this point questions start to get more complicated/contextual. Ex:
How can processes running in 2 threads communicate with each other?
How can processes running in 2 threads access/modify common state between them?
In the context of creating a simple game, one option is to use Queues to feed user inputs to the game and have the game process updates in a single thread. The following sample listens for the user inputting commands (Up, Down, Left, Right) on the main thread and adds valid commands to a queue. Valid commands are polled and processed in a different thread to update the location on the board.
Sample:
public static void main(String args[])
{
Board board = new Board();
BlockingQueue<Move> movesQueue = new ArrayBlockingQueue<>(100);
Scanner systemListener = new Scanner(System.in);
start(() -> routeBoardMovesToQueue(board, movesQueue)); /*route moves from the queue to the board in a new thread*/
while(true)
{
Optional<Move> nextMove = Move.resolve(systemListener.nextLine());
if(nextMove.isPresent())
movesQueue.offer(nextMove.get()); /*Write moves from System.in to the queue*/
else
System.out.println("Invalid Move Provided");
}
}
public static void routeBoardMovesToQueue(Board board, BlockingQueue<Move> movesQueue)
{
try
{
while(true)
{
Move next = movesQueue.poll(100_000, TimeUnit.DAYS);
if(next != null) board.performMove(next);
}
}
catch(InterruptedException ignored){ System.out.println("Stopping"); }
}
public static void start(Runnable processToRun)
{
Thread newProcess = new Thread(processToRun);
newProcess.setDaemon(true);
newProcess.start();
}
public static final class Board
{
private final Location location;
public Board(){ this.location = new Location(); }
public void performMove(Move move)
{
switch(move)
{
case Up: location.y += 1; break;
case Down: location.y -= 1; break;
case Right: location.x += 1; break;
case Left: location.x -= 1; break;
}
System.out.println("New Position: (" + location.x + ", " + location.y + ")");
}
public static class Location{ int x = 0; int y = 0; }
}
public enum Move
{
Up, Down, Left, Right;
public static Optional<Move> resolve(String move){ return Stream.of(Move.values()).filter(mv -> Objects.equals(move, mv.name())).findAny(); }
}
You should search "java multithreading" on your favourite search engine and compare your code with those examples
You will find that these people have (mostly) implemented the Runnable interface on their classes.
So
-- public class ChecksUserInput {
++ public class ChecksUserInput implements Runnable{
And run() was a method of that interface, that they had to implement.
Your version first runs the run method of the first class, then the other.
But when you implement the runnable interface, the both run methods will be called right after one another, without waiting for the first one to finish
You should search on your own and find more examples, or check the documentations for multithreading if you face any other issues
So after the wonderful help #BATIKAN BORA ORMANCI and #mike1234569 gave me along with this link https://www.geeksforgeeks.org/multithreading-in-java/ I was able to actually figure it out
package application;
public class Main {
public static void main(String[] args) {
CreateBoard board = new CreateBoard();
board.run();
Thread timer = new Thread(new Timer());
Thread input = new Thread(new ChecksUserInput());
timer.start();
input.start();
try {
timer.join();
input.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and I set my classes to implement Runnable as Batikan suggested

using Scanner and next() with println error

import java.util.Scanner;
import static java.lang.Thread.sleep;
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
}
public void run() {
System.out.println("asd");
}
public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
class RunnableDemo1 implements Runnable {
private Thread t;
private String threadName;
RunnableDemo1( String name){
threadName = name;
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Enter here:");
String x = in.nextLine();
System.out.println(x);
}
public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
RunnableDemo1 R1 = new RunnableDemo1( "Thread-1");
R1.start();
sleep(1000);
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Println will print a line to the command prompt but in.nexLine() (also tried in.next() does not recognize it. Is there any way I am able to print a string to the command prompt and have the scanner recognize it? Or something similar?
System.out.println shouldn't send anything to the server since it sends the String to the standard out only, usually the console, unless you've re-routed the standard out, something that I don't recommend that you do. Instead you need to actually send something to the server, perhaps in your notifyObservers method, but hard to say without your mcve.
In all this remains a very incomplete question until you improve it.
Edit: yes the Observable API shows that public void notifyObservers(Object arg) has an overload that accepts an Object parameter. Why not pass your String in there?
Edit 2: OK, you're confused, because that's not how you have one class communicate with another. Printing something out to the console will not trigger the System.in to update in another thread. Again, do what I stated above.

How do I navigate to UI while a process is running?

I'm currently writing a simple java app. I have a menu where I can perform different functions. What I'm wanting to do is execute a process, and while that process is running, still be able to navigate around the app, choosing different options from the menu. I also want to be able to stop the process from the menu.
So suppose I had this:
public class UserInterface {
Console c = System.console();
boolean quitFlag = false;
public void userInput()
{
String choice = c.readline("> ");
while(choice != "exit")
{
switch(choice){
case "1":
startProcess();
break;
case "2":
endProcess();
break;
}
}
public void startProcess()
{
int i = 0;
while(!quitFlag)
i = i + 1;
}
public void endProcess()
{
quitFlag = true;
}
}
How would I go about letting startProcess() continue while executing userInput()? Is there a general principle for this? How would I do it if startProcess() and endProcess() were in different classes?
There are several ways to do this but the simplest is via the Thread class. The Java docs for java.lang.Thread show examples, but the principle is that you place your separate process code inside a Thread subclass or in the run() method of a Runnable interface implementation which is passed to the Thread.
Call start() or run() on the thread to start processing. The UI thread continues independently.
Although Thread includes a stop() method, it is deprecated and the Java docs explain why. Best practice is to create your own method that sets a flag indicating that the process should end early, and then check this flag at frequent intervals.
Something like:
public class UserInterface {
MyProcessor processor = null;
...
public void startProcess() {
processor = new MyProcessor();
new Thread(processor).start();
}
public void endProcess() {
if (processor != null) {
processor.endProcess();
}
}
private class MyProcessor implements Runnable {
private boolean quitFlag = false;
#Override
public void run() {
int i = 0;
while (!quitFlag) {
i = i + 1;
}
}
public void endProcess() {
quitFlag = true;
}
}
}

java selenium thread synchronization bruteforce

This is for testing proposes (nothing bad)
I want to make a bruteforce program with Selenium 2 who breaks in a "0 to 10" password protected page
i have this (a tiny example not the actual code) ...
public class test implements Runnable {
static WebDriver driver;
test() {
StageLoader();
Thread t = new Thread(this);
t.start();
}
//starts firefox and goes to the page
private void StageLoader() {
driver = new FirefoxDriver();
driver.get("http://test.com/login.php");
}
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
bruteForce(i);
}
}
private void bruteForce(int i) {
driver.findElement(
By.name("password"))
.sendKeys(Integer.toString(i));
String output = driver.findElement(By.id("result")).getText();
if (output.indexOf("sucess") != -1) {
//stop
} else {
//continue
}
}
public static void main(String[] args) {
new FiberBrute();
}
}
it works perfectly but it lacks synchronization, i want it to go from 0 to 10 one by one and only continue with the next if !success, i already tried a lot to make this works with concurrency but i failed :( can you help me a little please ?
thanks in advance :D
The example code here as written should go 1 by 1, but it won't stop on success.
#Override
public void run() {
// Go until we run out of numbers or bruteForce comes back with 'true'
for (int i = 0; i <= 10 && !bruteForce(i); i++);
}
//Returns true if it found the password
private boolean bruteForce(int i) {
driver.findElement(
By.name("password"))
.sendKeys(Integer.toString(i));
String output = driver.findElement(By.id("result")).getText();
if (output.indexOf("sucess") != -1) {
//stop
return true;
} else {
//continue
return false;
}
}
In order for all 10 attempts to happen at once, bruteForce would need to be spawning threads, which it isn't doing here.

Categories