On my way to learn threads, this is working as intended
public class Game implements Runnable{
//FIELDS
private Thread t1;
boolean running;
//METHODS
public void start(){
running = true;
t1 = new Thread(this);
t1.start();
}
public void run(){
while (running){
System.out.println("runnin");
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And then, when I change the thread argument into
t1=new Thread (new Game());
The program doesn't enter the run method anymore.
Shouldn't they be the same? What should be the other way to substitute the "this" keyword?
EDIT: I'm calling the start method from another class.
Even setting the running variable to true after the instance has been created, it remains false:
public void start(){
t1 = new Thread(new Game());
running = true;
t1.start();
}
It enters the run() method, but it immediately returns from it, because the run method loops while running is true.
When calling new Game(), you're constructing a new different instance of Game, whose running field is false. So the loop doesn't loop at all:
public void start(){
running = true; // set this.running to true
t1 = new Thread(new Game()); // construct a new Game. This new Game has another, different running field, whose value is false
t1.start(); // start the thread, which doesn't do anything since running is false
}
Change it to
public void start(){
Game newGame = new Game();
newGame.running = true;
t1 = new Thread(newGame);
t1.start();
}
and it will do what you expect.
Not the same, in the first case if you call start() you'll create a new thread and start it, but when you use new Thread(new Game()) you need to call start() on the new thread.
Try this:
t1=new Thread (new Game());
t1.start();
It enters the run method but the variable 'running' is initialized to false for the new object created using new Game(). Hence, it does not print anything on the console.
If you want to create a thread for another instance of the object , you could try the following :
public class Game implements Runnable{
//FIELDS
private Thread t1;
boolean running;
//Constructor to set the running boolean
public Game(boolean running)
{
this.running = running;
}
//METHODS
public void start(){
running = true;
t1 = new Thread(new Game(running));
t1.start();
}
public void run(){
while (running){
System.out.println("runnin");
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Game implements Runnable{
//FIELDS
private Thread t1;
boolean running;
//METHODS
public void start(){
running = true;
t1 = new Thread(new Game());
t1.start();
}
public void run(){
running=true;
while (running){
System.out.println("runnin");
try {
Thread.sleep(17);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
class another{
public static void main(String s[]){
Game t=new Game();
t.start();
}
}
Related
This application has 2 threads the one shown here calls a method that pauses an auto clicker method every 4 seconds(just for ease) to do some mouse movement. I want it to stop the timer when you click the gui stop button.
Right now when you hit stop and then start again it then has two timers that will execute the code; and so on.
Action Listener Stuff.
class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(view.getBtnStart()))
{
autoClick.unTerminate();
bool = true;
getInfo();
}
if (e.getSource().equals(view.getBtnExit()))
{
System.exit(0);
}
if (e.getSource().equals(view.getBtnStop()))
{
bool = false;
autoClick.terminate();
}
}//end of actionPerformed
}//end of inner class
Thread
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
Timer timer = new Timer(4000, new ActionListener() {//301000 5minutes and 1second
#Override
public void actionPerformed(ActionEvent evt) {
autoClick.timeOverload();
}
});
//if (!bool){timer.stop();}
timer.setRepeats(true); //false only repeates once
timer.start();
}
});//end of t2
It calls the timeOverload method repeatedly.
Thanks for your time and helping a newbie out :).
Here is a quick sample of how to declare a instance outside of your thread and be able to control it outside of it.
public static void main(String[] args){
final Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("tick");
}
});
timer.setRepeats(true);
Thread t = new Thread(new Runnable() {
public void run() {
timer.start();
}
});
t.start();
try {
Thread.sleep(2600);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
timer.stop();
}
Basicly, you need to set the instance final to be used in a anonymous class (the ActionListener implementation).
Here, I just start the thread then pause the process for a few seconds and stop the timer.
Note that here, the Thread don't do anything else so it ends directly. You will need to tweek this a bit to match your needs but you have a working example.
EDIT : (DevilsHnd, if you post your answer, notify me, I will remove this part)
Using a flag (here in a Class)
public class Main {
public static void main(String[] args){
new Main();
}
boolean running = true;
public Main(){
final Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!running){
((Timer)e.getSource()).stop();
} else {
System.out.println("tick");
}
}
});
timer.setRepeats(true);
timer.start();
try {
Thread.sleep(2600);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
stop();
}
public void stop(){
running = false;
}
}
Calling the Main.stop() will set the flag to false, on each action performed, you check this flag, if it is false, you get the timer from the event (in the source) and stop it.
I want to make a simple space shooter game but it is not working well at the start. How it will be its end? Something is going wrong with my code. The overridden run() method of the Runnable interface is not working. Why the run method is not working as it should? Moreover any information about how to shoot more independent bullets. Here is my code. Thanks in advance.
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
public class GameWindow extends JFrame implements Runnable {
static final int WIDTH = 500;
static final int HEIGHT = 500;
static final String title = "East Game Development";
private boolean running = false;
private Thread thread;
GameWindow() {
setSize(new Dimension(WIDTH, HEIGHT));
getContentPane().setBackground(Color.BLACK);
setMaximumSize(new Dimension(WIDTH, HEIGHT));
setMinimumSize(new Dimension(WIDTH, HEIGHT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setResizable(false);
setVisible(true);
}
private synchronized void start() {
System.out.println("Debugging start method");
if (running) {
return;
}
running = true;
thread = new Thread();
thread.start();
}
private synchronized void stop() {
if (!running) {
return;
}
running = false;
try {
thread.join();
} catch (Exception ex) {
}
System.exit(1);
}
#Override
public void run() {
System.out.println("Debugging");
while (running) {
System.out.println("Working well...");
}
stop();
}
public static void main(String[] args) {
GameWindow gw = new GameWindow();
gw.start();
}
}
thread = new Thread();
thread.start();
You're creating a thread without passing it anything to run. The Thread constructor expects a Runnable as argument, and this runnable is what will be executed in the thread. You thus want
thread = new Thread(this);
thread.start();
Note, though, that your code is not thread-safe: the run() method reads the value of the running variable without synchonization. And it might thus see it as true aven if the stop() method has been called in another thread. You should use the stanard interruption mechanism to ask your thread to stop, and to check if the thread must continue to run:
public void stop() {
thread.interrupt();
}
public void run() {
while (!Thread.currentThread.isInterrupted()) {
...
}
}
When you create a thread, you should specify which runnable instance it will call run. In your case:
thread = new Thread(this);
thread.start();
thread = new Thread();
You are creating normal Thread and starting it. Why do you expect your run() method to run?
private synchronized void start() {
System.out.println("Debugging start method");
if (running) {
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
if u have only JFrame no really need to make it a runnable. just use these in main method:
gw.setVisible(true);
gw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
I am following a guide that shows how to create a Pong game. There is a part, where I am supposed to create a Thread, and call a function that moves the ball.
This is the code I created:
package com.ozadari.pingpong;
public class PingPongGame extends Thread {
private Ball gameBall;
private PingPongView gameView;
public PingPongGame(Ball theBall,PingPongView mainView)
{
this.gameBall = theBall;
this.gameView = mainView;
}
#Override
public void run()
{
while(true)
{
this.gameBall.moveBall();
this.gameView.postInvalidate();
try
{
PingPongGame.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}}
The thread is called and working, but it doesn't print anything. I tried to cancel the infinte loop and make the loop run 100 times. After I wait a while, it prints to the screen as it should be after 100 runs, but it doesn't print anything in the middle.
What is the problem? How can I fix it?
Unsure from the code you've posted but anyway, you can use a handler and have it run once every second like so (change the time to what you want):
Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//do your stuff here
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
http://developer.android.com/reference/android/os/Handler.html
You can also use a normal thread, and call start at the end.
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
I am trying to learn about thread and find some examples in the internet. This is a java class that output "hello, world" every 3 seconds. But I have a feeling that the part about creating a Runable object is redundant.
Instead of writing
Runnable r = new Runnable(){ public void run(){...some actions...}};
Can I put the method run() somewhere else for easy reading?
This is what I have:
public class TickTock extends Thread {
public static void main (String[] arg){
Runnable r = new Runnable(){
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
};
Thread thr = new Thread(r);
thr.start();
}
And this is what I want to accomplish
public static void main (String[] arg){
Runnable r = new Runnable() //so no run() method here,
//but where should I put run()
Thread thr = new Thread(r);
thr.start();
}
Can I put the method run() somewhere else for easy reading?
Yes you could create your own runnable like this
public class CustomRunnable implements Runnable{
// put run here
}
and then
Runnable r = new CustomRunnable () ;
Thread thr = new Thread(r);
From the Java threads tutorial, you can use a slightly different style:
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Just make your anonymous Runnable class an inner static class, like so:
public class TickTock {
public static void main (String[] arg){
Thread thr = new Thread(new MyRunnable());
thr.start();
}
private static class MyRunnable implements Runnable {
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
}
}
Or since TickTock already extends Thread in your example code, you can just override its run method:
public class TickTock extends Thread {
public static void main (String[] arg){
Thread thr = new TickTock();
thr.start();
}
#Override
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
}
Thread thread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yippi);
final Handler hn=new Handler();
final TextView text=(TextView)findViewById(R.id.TextView01);
final Runnable r = new Runnable()
{
public void run()
{
text.settext("hi");
}
};
thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1750);
hn.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
thread.stop();}
The code here. I can not stop the runnable thread. Also, thread.stop() and thread.destroy() are deprecated. Can somebody help me? And also I don't understand how to stop the thread with the thread.interrupt() method. What's wrong?
The JavaDoc for Thread.stop() lists the following article as explanation for why stop() is deprecated: http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).
interrupt() is more suitable to stop some Thread from waiting for something, that is probably not coming anymore. If you want to end the thread, it's best to let its run() method return.
Create a boolean variable to stop the thread and use it in while(boolean) instead of while(true).
You can use Thread.interrupt() to trigger the InterruptedException within your thread. I've added code below that demonstrates the behavior. The mainThread is where your code would be and the timer Thread is just used to demonstrate delayed triggering of the interrupt.
public class Test {
public static void main(String[] args) {
final Thread mainThread = new Thread() {
#Override
public void run() {
boolean continueExecution = true;
while (continueExecution) {
try {
sleep(100);
System.out.println("Executing");
} catch (InterruptedException e) {
continueExecution = false;
}
}
}
};
mainThread.start();
Thread timer = new Thread() {
#Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping recurring execution");
mainThread.interrupt();
}
};
timer.start();
}
}
You can use interrupt method of Thread to try stop a thread, like below code.
May be it`s useful to you.
public class InterruptThread {
public static void main(String args[]){
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
System.out.println("Thread is Runing......");
sleep(1000);
}
} catch (InterruptedException e) {
// restore interrupted status
System.out.println("Thread is interrupting");
Thread.currentThread().interrupt();
}
}
};
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Will Interrupt thread");
thread.interrupt();
}
}