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.
Related
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
Im having problems with my Printer-Counter School Problem. Its supposed to be a multithreading application and runs fine so far. But when I running it the second or third time it wont work anymore.. No error message. Looks like Threads sleep forver or so. Also when I test it with a JUnit test it wont work. But sometimes it does... wich is already strange itself.
public class CounterPrinter {
public static void main(String[] args) throws InterruptedException {
if (args.length != 2) {
System.out.println("Usage: CounterPrinter <min> <max>");
System.exit(1);
}
Storage s = new Storage();
Printer d = new Printer(s, Integer.parseInt(args[1]));
Counter z = new Counter(s, Integer.parseInt(args[0]), Integer.parseInt(args[1]));
z.start();
d.start();
z.join();
d.join();
Thread.sleep(5000);
}
}
public class Printerextends Thread {
private Storage storage;
private Integer ende;
Printer(Storage s, Integer ende) {
this.storage = s;
this.ende = ende;
}
#Override
public void run() {
while (storage.hasValue()) {
try {
System.out.print(speicher.getValue(ende) + " ");
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Counter extends Thread {
private Storage speicher;
private int max, min;
Counter(Storages, int min, int max) {
this.storage = s;
this.max = max;
this.min = min;
}
#Override
public void run() {
for (int i = min; i <= max; i++) {
try {
storage.setValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Storage implements StorageIf {
private Integer wert;
private boolean hasValue = false;
#Override
public synchronized Integer getValue(Integer ende) throws InterruptedException {
if(wert.equals(ende)){
hasValue = false;
return wert;
}else {
while (!hasValue()) {
wait();
}
hasValue = false;
notifyAll();
return wert;
}
}
#Override
public synchronized void setValue(Integer wert) throws InterruptedException {
while (hasValue()){
wait();
}
hasValue = true;
this.wert = wert;
notifyAll();
}
#Override
public boolean hasValue() {
return hasValue;
}
}
Hope someone can spot a mistake I made :(
Thanks a lot!!!
The problem is that you conflate 2 states :
there is currently a value available
there will be no more values
Add an hasEnded() method to your Storage class, checking if the end value has been reached. Make sure to synchronize this method, as well as the hasValue() method. Synchronization needs to be done on both read and write access!
Then make Printer's while loop check hasEnded, rather than hasValue.
Finally : get rid of all the sleep() calls.
Your own answer, solving the problem with sleep, is not a real solution. A thread safe program does not depend on a computer's performance to function correctly.
z.start();
z.sleep(100);
d.start();
Putting a delay between starting the tow Threads solved the problem for me. My Computer was probably too fast down the road in Thread z before it even started Thread d. Thats why it hung itself up in 50% of the time.
Thanks to everyone tho :)
why my thread can't be stopped???
class Threadz {
class runP implements Runnable {
int num;
private volatile boolean exit = false;
Thread t;
public runP() {
t = new Thread(this, "T1");
t.start();
}
#Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
num++;
try {
t.sleep(200);
} catch(InterruptedException e) {}
}
}
public void stop() {
exit = true;
}
}
public static void main(String[] a) {
runP rp = new Threadz().new runP();
if(rp.num == 1) {rp.stop();}
}
}
if i use rp.num == 0, the thread can be stopped immediately. But, why when i changed the rp.num == x (x is any number greater than 0) the thread cannot stop? please help me solve this thing... thanks for any helps.
Because this code is not executed in the run() method of the thread :
runP rp = new Threadz().new runP();
if (rp.num == 1) {
rp.stop();
}
It works with 0 as the default value of int is 0.
But it is not necessarily true in all executions of the application as the thread of runP could run and incrementnum before the check : if (rp.num == 0)
Move the stop condition in the run method of the runP thread :
#Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
num++;
try {
t.sleep(200);
} catch(InterruptedException e) {}
if (rp.num == 1) {
exit = true;
}
}
}
I'm sure if you run the program many many times, It'll be a case when the program actually stops.
The reason is at the time you run the program there is much more chance of executing
if(rp.num == 1) {rp.stop();}
before num++ in your run() method changes value.
However by chance you may come across a case that the loop in your run method gets executed before that if statement in your main method.
one way to make sure this happens is to continuously checking for the condition:
e.g.
public static void main(String[] a) {
runP rp = new Threadz().new runP();
while(true){
if(rp.num == 1) {
rp.stop();
break;
}
}
}
Statement below is getting executed before the thread starts executing the run method.
if(rp.num == 1) {rp.stop();}
Add Thread.sleep before the above statement, it works fine as it will execute this statement after starting the loop.
public static void main(String[] a) {
runP rp = new Threadz().new runP();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rp.num > 1) {rp.stop();}
}
I have made it >1 to test.
Checking rp.num == 1 would have to happen exactly at a point where rp.num is exactly one, which is rather unlikely.
In your main method, you start a thread which increments num every 200 ms. Afterwards, you check if num == 1, but when exactly this code is executed depends on a lot of factors you cannot really control (scheduling of the OS, etc...). This might be after 10 ms (where the value would be 1), but could also be after 300 ms (when the value is already 2). Also when the thread is exactly started is unsure. Therefore it is also possible that your thread only starts after the test. You can easily test this by replacing the check if(rp.num == 1) {rp.stop()}; with a simple print statement System.out.println(rp.num). If you additionally wait for some time before printing, you might get a better feeling of what I am talking about.
Supposing you would like to stop a runnable from outside, I suggest to use something like the Observer pattern:
class MyRunnable implements Runnable {
private final MyListener l;
private volatile boolean exit;
int num;
public MyRunnable(MyListener l) {
this.l = l;
exit = false;
}
#Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
l.check(num++);
try {
t.sleep(200);
} catch(InterruptedException e) {}
}
}
public void stop() {
exit = true;
}
}
class MyListener {
private final threshold;
public MyListener(int x) {
this.threshold = x;
}
public void check(MyRunnable r, int num) {
if (num >= threshold)
r.stop();
}
}
and your main method would look something like
public static void main(String[] args) {
MyListener l = new MyListener(1);
Runnable r = new MyRunnable(l);
new Thread(r).start();
}
I am trying to solve Philosopher Problem using Future in Java.
public class Philo implements Callable<PhiloStatus> {
private PhiloStatus status;
private Philo leftPhilo;
private Philo rightPhilo;
private String name;
public Philo(String name) {
status = PhiloStatus.THINKING;
this.name =name;
}
public void setLeftPhilo(Philo leftPhilo) {
this.leftPhilo = leftPhilo;
}
enter code here
public void setRightPhilo(Philo rightPhilo) {
this.rightPhilo = rightPhilo;
}
#Override
public PhiloStatus call() throws Exception {
if (leftPhilo.getStatus() == PhiloStatus.THINKING
&& rightPhilo.getStatus() == PhiloStatus.THINKING) {
this.status =PhiloStatus.DINING;
System.out.println("Dininig "+this);
return PhiloStatus.DINING;
}
this.status =PhiloStatus.THINKING;
System.out.println("Thinking "+this);
return PhiloStatus.THINKING;
}
public PhiloStatus getStatus() {
return status;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return name;
}
}
Starting point of the program
public class Start {
/**
* #param args
*/
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
Philo[] philosophers = new Philo[5];
for (int i = 0; i < 5; ++i)
philosophers[i] = new Philo(""+i);
for (int i = 0; i < 5; ++i) {
philosophers[i].setLeftPhilo(philosophers[(i + 4) % 5]);
philosophers[i].setRightPhilo(philosophers[(i + 1) % 5]);
executorService.submit( philosophers[i]);
}
}
}
But seems like once Callable is finished executing , it returns the same result.
I doubt now that it might not be possible to solve this problem using Future?
Could anyone please shed a light on this.
class Philo implements Runnable{
#Override
public void run(){
while(true){
if(Thread.interrupted()){
break;
}
//dining logic
}
}
}
The solution can be a loop which executes till someone interrupts the Philosopher.
A Callable computes the result once, then returns the value for this computation. So if you want to compute something again, you need to run the Callable again.
void diningAttempt() {
Future<PhiloStatus>[] results = new Future<PhiloStatus>[philosophers.length];
for (int i = 0; i < philosophers.length; ++i) {
results[i] = executor.submit(philosophers[i]);
}
for (int i = 0; i < philosophers.length; ++i) {
System.out.println(results[i].get());
}
}
And then somewhere else:
while (dining) {
diningAttempt();
}
As you can probably see, this is slightly different to what the “Dining Philosopher” problem actually describes, which is the problem of threads being able to do something at any time, as in this case you have separated dining attempts, which then most likely succeed all the time.
If you want those threads to actually lock, you need to give them the ability to run in parallel all the time, which means a Callable is not the correct way to simulate this issue. Nevertheless your attempt has a valuable lesson to learn: if you manage to put your work in separate batches like above, threads are much less likely to lock. And this is why the Executor has been invented in the first place.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I was trying to write a code where multiple threads call methods on a shared object to increment/decrement/print a counter stored in it. What I also want are these numbers to vascillate between 0 and 8. That is the output might look like something below:
0123234567654566677877666655....
Can somebody look at what I have cranked out and give me some pointers on whether I am on the right track:
My shared object:
public class SyncObj{
private int i;
public synchronized void inc(){
if(i<8)
i++;
}
public synchronized void dec(){
if(i > 0)
i--;
}
public synchronized void print(){
System.out.print(i);
}
}
To prevent starvation on the print and to make sure every inc/dec gets printed, I can have a private variable called hasPrinted and rewrite the class as follows:
public class SyncObj{
private int i;
//Changed Boolean to boolean as Keith Randall pointed out
private boolean hasPrinted = false;
public synchronized void inc(){
if(i<8 && hasPrinted){
i++;
hasPrinted = false;
}
}
public synchronized void dec(){
if(i > 0 && hasPrinted){
i--;
hasPrinted = false;
}
}
public synchronized void print(){
System.out.print(i);
hasPrinted = true;
}
}
Can somebody go over the above snippet and review it for pitfalls and gotchas?
Thanks
You should get used to using a queue for printing.
public class SyncObj {
private volatile int i;
private BlockingQueue<Integer> q = new LinkedBlockingQueue<Integer>();
public synchronized void inc() {
if (i < 8) {
i++;
q.add(i);
}
}
public synchronized void dec() {
if (i > 0) {
i--;
q.add(i);
}
}
public void print() {
for (Integer i = q.poll(); i != null; i = q.poll()) {
System.out.print(i);
}
}
private static volatile boolean stop = false;
public static void main(String[] args) throws InterruptedException {
final SyncObj o = new SyncObj();
new Thread(new Runnable() {
#Override
public void run() {
while (!stop) {
o.inc();
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while (!stop) {
o.dec();
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while (!stop) {
o.print();
}
}
}).start();
Thread.currentThread().sleep(1000);
stop = true;
}
}
My output looks like this:
1012345678765432101234567876543210123456787654321012345678765432101234567876543210123456787654321012345678
Boolean -> boolean, no point in having an object instead of a primitive type.
Your first code is fine. Your second code doesn't solve your requirements of preventing starvation or making sure every inc/dec gets printed. Why not just have inc/dec print the value itself?