Okay, so I want it so if player typs ::help, the method from RequestHelp.java will run,
Commandif (playerCommand.startsWith("help") && (c.playerRights >= 0)) {
c.sendMessage("A staff member has been contacted, please wait.");
(right here is where I want the method from the other class to run'
}
this is the method from RequestHelp.java
public static void callForHelp(Client c) {
if (System.currentTimeMillis() - c.lastRequest < 30000) {
c.sendMessage("It has only been "+ getTimeLeft(c) +" seconds since your last request for help!");
c.sendMessage("Please only request help from the staff every 30 seconds!");
if (!requestingHelp) {
c.setSidebarInterface(3, 3213);
c.getPA().sendFrame106(3);
}
return;
}
requestingHelp = true;
otherPlayer = c.playerName;
c.lastRequest = System.currentTimeMillis();
setInterface(c);
PlayerHandler.messageAllStaff(Misc.optimizeText(getPlayer().playerName) +" needs help, their cords are: "+ playerCoords() +".", true);
}
RequestHelp helper = new RequestHelp();
if(playerCommand.equals("::help")) {
helper.callForHelp(client);
}
This should work.
Related
I wanted to say for a school project in Greenfoot, that if a rover encounters a system error, it should output this and then wait a short time and then terminate the current method. However, the pause is marked with the following error code: unreported exception java. lang. InterupptedException; must be cought or declared to be thrown, as I am very new to Java I have no idea what to change. Besides, he should then end the method, but with the current command the whole scenario is ended.
"
public Rover (String pname, char pfrequenz, int penergie)
{
energie = penergie;
name = pname;
temp = 15 ;
distance = 0;
systemcheck = true;
frequenz = pfrequenz ;
}
public void check()
{
if (markeVorhanden())
{
energie = energie + 100;
}
if (energie == 0){
systemcheck = false;
}
if (systemcheck = false){
nachricht("System Failure");
java.util.concurrent.TimeUnit.SECONDS.sleep(2);
System.exit(0);
}
if (distance > 100){
nachricht("Congrats you have passed 100");
}
anzeige.anzeigen("Akku: "+energie+ " %");
}
Try this
import java.io.*;
public class Yourclass{
public void Rover (String pname, char pfrequenz, int penergie)
{
Integer energie = penergie;
String name = pname;
Integer temp = 15 ;
Integer distance = 0;
boolean systemcheck = true;
char frequenz = pfrequenz ;
}
public void check() throws IOException
{
if (markeVorhanden())
{
energie = energie + 100;
}
if (energie == 0){
systemcheck = false;
}
if (systemcheck = false){
nachricht("System Failure");
throw new IOException("sorry device error");
}
if (distance > 100){
nachricht("Congrats you have passed 100");
}
anzeige.anzeigen("Akku: "+energie+ " %");
}
public static void main(String []args) throws InterruptedException
{
Yourclass demo= new Yourclass();
System.out.println("Hello World");
try{
demo.check();
}
catch(Exception e)
{
Thread.sleep(2000);
System.out.println("function stopped");
}
}
}
You will have to read up on exception handling in Java. The sleep method may get interrupted and may thus raise an InterruptedException. You can either forward this exception or ignore it.
To forward the exception, declare the function a
public void check() throws InterruptedException
but then callers of this function will have to deal with that potential exception. Since interrupted does not look a severe problem here (the sleep is just a bit shorter than the two seconds), it may be fine to ignore the exception:
try { java.util.concurrent.TimeUnit.SECONDS.sleep(2); }
catch (InterruptedException ignored) {}
In order to just return from the current method use return instead of System.exit()
I created a project for studying purposes that simulates a restaurant service using Threads. There is a Thread for Cook(s) to prepare a meal and another Thread for Waiter(s) to serve the meal. When I tested it with 1 cook and 5 waiters, it worked fine. But when I increase the number of cooks, the program runs indefinitely. What is wrong? Here is the code:
Class Main
package restaurant;
import java.util.concurrent.Semaphore;
public class Main {
public static int MAX_NUM_MEALS = 5;
public static int OLDEST_MEAL = 0;
public static int NEWEST_MEAL = -1;
public static int DONE_MEALS = 0;
public static int NUM_OF_COOKS = 1;
public static int NUM_OF_WAITERS = 5;
public static Semaphore mutex = new Semaphore(1);
static Cook cookThreads[] = new Cook[NUM_OF_COOKS];
static Waiter waiterThreads[] = new Waiter[NUM_OF_WAITERS];
public static void main(String[] args) {
for(int i = 0; i < NUM_OF_COOKS; i++) {
cookThreads[i] = new Cook(i);
cookThreads[i].start();
}
for(int i = 0; i < NUM_OF_WAITERS; i++) {
waiterThreads[i] = new Waiter(i);
waiterThreads[i].start();
}
try {
for(int i = 0; i < NUM_OF_COOKS; i++) {
cookThreads[i].join();
}
for(int i = 0; i < NUM_OF_WAITERS; i++) {
waiterThreads[i].join();
}
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("All done");
}
}
Class Cook
package restaurant;
public class Cook extends Thread{
private int id;
public Cook(int id) {
this.id = id;
}
public void run() {
while(true) {
System.out.println("Cook " + id + " is prepearing meal");
try {
Thread.sleep(1000);
Main.mutex.acquire();
Main.NEWEST_MEAL++;
Main.mutex.release();
Main.mutex.acquire();
Main.DONE_MEALS++;
Main.mutex.release();
System.out.println("Cook " + id + " has finished the meal");
if(Main.DONE_MEALS == 5) {
System.out.println("Cook " + id + " has finished his job");
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Class Waiter
package restaurant;
public class Waiter extends Thread{
private int id;
public Waiter(int id) {
this.id = id;
}
public void run() {
while(true) {
System.out.println("Waiter " + id + " will check if there is any meal to serve");
if(Main.NEWEST_MEAL >= Main.OLDEST_MEAL) {
try {
Main.mutex.acquire();
Main.OLDEST_MEAL++;
Main.mutex.release();
System.out.println("Waiter " + id + " is picking up meal");
Thread.sleep(500);
System.out.println("Waiter " + id + " has delivered the meal to client");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(Main.DONE_MEALS == 5) {
System.out.println("Waiter " + id + " has finished his job");
break;
}
System.out.println("No meal to serve. Waiter " + id + " will come back later");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Two issues:
Because you have two cooks, one of your cooks likely won't see Main.DONE_MEALS == 5. It will jump from 4 to 6 because of the other cook. Instead, check for Main.DONE_MEALS >= 5.
There is no guarantee that the cook or waiter threads will see the updates to Main.DONE_MEALS. Instead, consider having a private static final AtomicInteger field. The AtomicInteger class is a thread-safe integer implementation that enables other threads to see it in a thread-safe way.
The traditional fix would be:
a) You have to use the lock (mutex) not only when you write, but also when you read - otherwise it won't work correctly.
Just imagine you agreed on a signal to indicate if the bathroom is busy, but some just decide to ignore it - won't work!.
b) Check the condition before you do something.
Once you acquire the lock, you don't know the state so you should first check it before you proceed to make another meal. If you first check if there are already 5 done meals and only produce meals if there aren't yet 5, it should fix this problem, and you should only ever see done_meals <= 5 (you should review other parts of the code because it has similar problems, though).
Like others have mentioned, there are cleaner ways to write this but IMO your code is very suited for practice and understanding, so I'd try that rather than jumping for things like AtomicInteger.
I have developed a client/server chat application using Java and I wish to know how can I remove a user from an array. When a specific client log-in the username is saved in username array and client ID in client array. To allow the server to accept multiple clients, I am using threads. Now can anyone guide me on how to remove a user from the array and also close the connection for that user.
Adding a new client and saving the ID in client array
public class AddClient implements Runnable {
Thread t;
AddClient(String tot) {
t = new Thread(this, tot);
t.start();
}
public void run() {
while (true) {
try {
try {
waitClient();
} catch (Exception ex) {
ex.printStackTrace();
}
for (int i = 0; i < client.length; i++) {
if (client[i] == 0) {
client[i] = i + 1;
id = i;
break;
}
}
//set stream to send and receive data
out[client[id]] = new ObjectOutputStream(connect.getOutputStream());
out[client[id]].flush();
in[client[id]] = new ObjectInputStream(connect.getInputStream());
The username is saved in the username array
username[client[id]] = cm.sender; //Add user in username[] array
Removing user
public synchronized void removeUser(int number) {
int position = number;
System.out.println("Server removing user " + username[number] + "which is client " + number);
for (int i = 0; i <= client.length; i++) {
if (position == client[i]) {
System.out.println("User to be remove found");
try {
client[i + 1] = client[i];
in[position].close();
out[position].close();
username[position] = null;
position = position - 1;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to use HashTable to add and remove the client
public class ChatServerProtocol {
private String nick;
private AddClient a;
private Hashtable<String, AddClient> nicks = new Hashtable<String, AddClient>();
private boolean add_nick(String nick, AddClient a) {
if (nicks.containsKey(nick)) {
return false;
} else {
nicks.put(nick, a);
return true;
}
}
private boolean remove_nick(String nick, AddClient a) {
if (!(nicks.containsKey(nick))) {
return false;
} else {
nicks.remove(nick);
return true;
}
}
public ChatServerProtocol(AddClient a) throws IOException {
nick = null;
a = a;
}
But now how do I call the method add_nick. Whenever a client log-in the username is sent to the server and the server reads it as cm.sender. I also need to include the thread variable. So how to add the username so that later i can remove it.
ChatServerProtocol.add_nick(cm.sender);
No, saving in database won't be a good idea.. Remember you are saving details only for the length of the session and basic concept of database is to use it after the session. What happens if your session gets interruped because of network issues etc?
Just use Map instead of plain arrays, using key as client ID and value as username.. removing username will be a plain call such as map.remove(clientID);
EDIT AS YOU ASKED: Note that this code is not complete and only as much as you gave..
public class AddClient implements Runnable {
Thread t;
private Map<int, String> users = new HashMap <int, String>();
AddClient(String tot) {
t = new Thread(this, tot);
t.start();
}
public void run() {
while (true) {
try {
try {
waitClient();
} catch (Exception ex) {
ex.printStackTrace();
}
int clientId = users.size() + 1;
users.put(clientId, cm.sender);
//set stream to send and receive data
out[clientId] = new ObjectOutputStream(connect.getOutputStream());
out[clientId].flush();
in[clientId] = new ObjectInputStream(connect.getInputStream());
REMOVE USER METHOD
public synchronized void removeUser(int number) {
if(users.containsKey(number)) {
System.out.println("Server removing user " + users.get(number) + "which is client " + number);
users.remove(number);
} else {
System.out.println("User not in session");
}
}
I have a program that simulates Gates to a ship. They run in threads. The idea is to let them run and pause during a random moment in the run method to simulate persons passing. This is done by all threads, meanwhile the main thread is waiting for notification and checking if the ship is getting full when notified by the threads that they added a person passing through the gate the main thread checks again if the ship is full. The program has three classes:
A counter:
public class Counter {
private int currentValue[];
private int maxValue;
public Counter(int[] nrOfPeople, int max) {
currentValue = nrOfPeople;
currentValue[0] = 0;
maxValue = max;
}
public synchronized void addPersons(int nr_p) {
currentValue[0] += nr_p;
}
public synchronized int getValue() {
return currentValue[0];
}
public synchronized boolean isFull() {
if(currentValue[0] < maxValue)
return false;
return true;
}
}
A Gate Class:
public abstract class Gate implements Runnable {
int nrOfPassengers;
int gatenr;
int gatesize;
Counter c;
private Thread t;
private Random r;
private boolean blocked; /* suspends people from passing */
public Gate(Counter c, int nr) {
this.c = c;
gatenr = nr;
this.open();
r = new Random();
t = new Thread(this);
t.start();
}
public void setGatesize(int size) {
gatesize = size;
}
public void close() {
blocked = true;
}
public void open() {
blocked = false;
}
public int getNoOfPassangers() {
return nrOfPassengers;
}
public int getId() {
return gatenr;
}
#Override
public void run() {
while(!blocked) {
int waitTime = (r.nextInt(5) + 1) * 1000; /* between 1-5 seconds */
System.out.println("Person-Gate " + gatenr + ": adding one to " + c.getValue());
try {
/* bigger throughput => amount can vary */
if(gatesize > 1) {
int persons = r.nextInt(gatesize)+1;
c.addPersons(persons);
nrOfPassengers += persons;
} else {
c.addPersons(1);
nrOfPassengers++;
}
Thread.sleep(waitTime);
} catch (InterruptedException e) {
System.out.println("Person-Gate " + gatenr + ": was interrupted adding person");
e.printStackTrace();
}
System.out.println("Person-Gate " + gatenr + ": added one to " + c.getValue());
t.notify();
}
}
public void join() {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And a Simulator that runs the main method:
/*
* This class simulates cars and persons- entering a ferry.
*/
public class Simulator {
public static final int MAX = 30;
public static void main(String[] args) {
int nrOfPeople[] = new int[1]; /* array of size one for keeping count */
ArrayList<Gate> gates = new ArrayList<Gate>();
Counter counter = new Counter(nrOfPeople, MAX);
Thread mainThread = Thread.currentThread();
/* adding 3 person-gates */
for(int i=1; i<4; i++) {
gates.add(new PersonGate(counter, i));
}
/* let all gates work as long as passengers is under MAX */
while(!counter.isFull()) {
try {
mainThread.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Announcement: Ship is full!");
/* wait for child threads to finish */
for(Gate g: gates) {
g.close();
try {
g.join();
} catch (Exception e) { /* InterruptedException */
e.printStackTrace();
}
System.out.println(g.getNoOfPassangers() + " passed through gate nr " + g.getId());
System.out.println(counter.getValue() + " has passed in total");
}
}
}
Im getting a error
Person-Gate 1: adding one to 0
Person-Gate 2: adding one to 1
Person-Gate 3: adding one to 2
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at Simulator.main(Simulator.java:24)
Person-Gate 3: added one to 3Exception in thread "Thread-3"
Does anyone now whats going on?
You can only call wait and notify/notifyAll from within synchronized blocks.
t.notify();
You are notifying wrong monitor. This exception occurs, when you do not wrap monitor object with synchronize section. However, objects which you are using for notify and for wait methods are different. Create new Object() monitor and pass it to the constructor of Gate.
Also you can take a look at CountDownLatch, it does exactly what you are trying to achieve.
You must own the monitor of the object on which you call wait or notify. Meaning, you must be in a synchonize-Block, like
synchronized( objectUsedAsSynchronizer) {
while ( mustStillWait) {
objectUsedAsSynchronizer.wait();
}
}
This has been the subject of many other questions.
I'm having a bit of a problem with writing a multithreaded algorithm in Java. Here's what I've got:
public class NNDFS implements NDFS {
//Array of all worker threads
private Thread[] threadArray;
//Concurrent HashMap containing a mapping of graph-states and
//algorithm specific state objects (NDFSState)
private ConcurrentHashMap<State, NDFSState> stateStore;
//Whether the algorithm is done and whether a cycle is found
private volatile boolean done;
private volatile boolean cycleFound;
/**
Constructor that creates the threads, each with their own graph
#param file The file from which we can create the graph
#param stateStore Mapping between graph-states and state belonging to our algorithm
#param nrWorkers Number of working threads we need
*/
public NNDFS(File file, Map<State, NDFSState> stateStore, int nrWorkers) throws FileNotFoundException {
int i;
this.stateStore = new ConcurrentHashMap<State, NDFSState>(stateStore);
threadArray = new Thread[nrWorkers];
for(i=0;i<nrWorkers;i++){
Graph graph = GraphFactory.createGraph(file);
threadArray[i] = new Thread(new NDFSRunnable(graph, i));
}
}
/**
Class which implements a single thread running the NDFS algorithm
*/
class NDFSRunnable implements Runnable{
private Graph graph;
//Neccesary as Java apparently doesn't allow us to get this ID
private long threadId;
NDFSRunnable(Graph graph, long threadId){
this.graph = graph;
this.threadId = threadId;
}
public void run(){
try {
System.out.printf("Thread id = %d\n", threadId);
//Start by executing the blue DFS for the first graph
mcdfsBlue(graph.getInitialState(), threadId);
} catch (CycleFound e) {
//We must catch all exceptions that are thrown from within our thread
//If exceptions "exit" the thread, the thread will silently fail
//and we dont want that. We use 2 booleans instead, to indicate the status of the algorithm
cycleFound = true;
}
//Either the algorithm was aborted because of a CycleFound exception
//or we completed our Blue DFS without finding a cycle. We are done!
done = true;
}
public void mcdfsBlue(State s, long id) throws CycleFound {
if(done == true){
return;
}
//System.out.printf("Thread %d begint nu aan een dfsblue\n", id);
int i;
int counter = 0;
NDFSState state = stateStore.get(s);
if(state == null){
state = new NDFSState();
stateStore.put(s,state);
}
state.setColor(id, Color.CYAN);
List<State> children = graph.post(s);
i = state.incNextBlue();
while(counter != children.size()){
NDFSState child = stateStore.get(children.get(i%children.size()));
if(child == null){
child = new NDFSState();
stateStore.put(children.get(i % children.size()),child);
}
if(child.getLocalColor(id) == Color.WHITE && !child.isRed()){
mcdfsBlue(children.get(i % children.size()), id);
}
i++;
counter++;
}
if(s.isAccepting()){
state.incRedDFSCount();
mcdfsRed(s, id);
}
state.setColor(id, Color.BLUE);
}
public void mcdfsRed(State s, long id) throws CycleFound {
if(done == true){
return;
}
int i;
int counter = 0;
NDFSState state = stateStore.get(s);
state.setPink(id, true);
List<State> children = graph.post(s);
i = state.incNextRed();
while(counter != children.size()){
NDFSState child = stateStore.get(children.get(i%children.size()));
if(child == null){
child = new NDFSState();
stateStore.put(children.get(i%children.size()),child);
}
if(child.getLocalColor(id) == Color.CYAN){
throw new CycleFound();
}
if(!child.isPink(id) && !child.isRed()){
mcdfsRed(children.get(i%children.size()), id);
}
i++;
counter++;
}
if(s.isAccepting()){
state.decRedDFSCountAndWait();
}
state.setRed();
state.setPink(id, false);
}
}
public void init() {}
public void ndfs() throws Result {
int i;
done = false;
cycleFound = false;
for(i=0;i<threadArray.length;i++){
System.out.printf("Launch thread %d\n",i);
threadArray[i].run();
}
try {
for(i=0;i<threadArray.length;i++){
threadArray[i].join();
}
} catch (InterruptedException e) {
}
//We want to show the result by throwing an exception (weird, but yeah :-/)
if (cycleFound) {
throw new CycleFound();
} else {
throw new NoCycleFound();
}
}
}
However, when I run this, it seems like the first thread is called, completes, and then the next is called etc. What I want obviously, is that all threads are started simultaneously! Otherwise the algorithm has very little use...
Thanks for your time/help!
Regards,
Linus
Use threadArray[i].start(); to launch your thread.
If you use threadArray[i].run();, all it does is call the method normally, in the same thread as the caller.