Need some help

0 adam kido · August 26, 2014
Hi folks,
It's about multithreading
I have two codes that do the same work, but wtitten in different ways.

In the first one i start a thread by extending the Thread class and it works perfectly.


import java.util.Scanner;

class Test extends Thread {

    private volatile boolean go = true;
    @Override
    public void run() {
        while (go) {
            System.out.println("It's already starting");
            try {
                Thread.sleep(100);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    public void enough() {
        go = false;
    }
}

public class Main {

    public static void main(String[] args) {

        Test t1 = new Test();
        t1.start();
        new Scanner(System.in).nextLine();
        t1.enough();

    }

}




 In the seconde one i start a thread by implementing Runnable interface. But i got error when i try to call enough() method (last line in code).
The error is : The method enough() is undefined for the type Thread.
I really don't know how to fixe this.

import java.util.Scanner;

class Test implements Runnable {

    private volatile boolean go = true; //

    @Override
    public void run() {
        while (go) {
            System.out.println("It's already starting");
            try {
                Thread.sleep(100);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    public void enough() {
        go = false;
    }
}

public class Main2 {

    public static void main(String[] args) {

        Thread t1 = new Thread(new Test());
        t1.start();
        new Scanner(System.in).nextLine();
        t1.enough();

    }

}





Post a Reply

Replies

Oldest  Newest  Rating
0 Pere Garau Burguera · August 27, 2014
You can't call enough() there because that method is from the Test class, and you are creating a Thread object, not a Test object. The two things I can think of that you can do is to do it extending the Thread class and the other one would be to call the enough() method within the run() method in the Test class, because I don't see here a difference between calling it on the main methid or out of it. 
  • 1

Java / Android Development

107,307 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator