简体   繁体   中英

Thread.start is not found

I have a thread that I have created

List<String> list_of_stocks = Arrays.asList("AAPL", "NFLX");
StockThread stockthread = new StockThread(list_of_stocks);
stockthread.start();

and this StockThread is defined as:

public class StockThread implements Runnable {

List<String> list_of_stocks;

public StockThread(List<String> list_of_stocks){
    this.list_of_stocks = list_of_stocks;
}
@Override
public void run() {
        /*  So this thread simply has a */
        StockObserver so = new StockObserver(this.list_of_stocks, 1);

        so.getStockPrices();
 }
}

but the start() method of the stockthread shows up as 'could not resolve symbol'.

I do not understand what is to blame. This should be an accessible method as I have implemented runnable no?

The correct way to create threads and start them using the thread class StockThread is to use one of the following ways - an example:

A thread can be defined and started using two different ways:

  1. Implementing the Runnable interface
  2. Extending the Thread class

1. Implementing Runnable:

Public class MyRunnable implements Runnable {

    @Override
    public void run() {
        // code to execude in the thread
    }
}

Instantiate and start the threads (two of them):

MyRunnable runnable = new MyRunnable();
Thread myThread1 = new Thread(runnable);
myThread1.start();
Thread myThread2 = new Thread(runnable);
myThread2.start();

The advantage of using the first approach is that the runnable class can still be extended.

2. Extending the Thread class:

public class MyThread extends Thread {

    @Override
    public void run() {
        // code to execude in the thread
    }
}

Instantiate and start the threads:

MyThread myThread1 = new MyThread();
myThread1.start();
MyThread myThread2 = new MyThread();
myThread2.start();

Note that any thread can only be started once.
Links to the APIsjava.lang.Thread and Runnable .

To clarify: your StockThread is implementing Runnable instead of extending Thread.

Runnable doesn't have a start method.

You could rename StockThread to StockRunnable and use run.

This will compile but may not yield the expected result.

If you want multi threading to occur, calling the run method won't work (as it will run the runnable in your current thread).

You can call new Thread(runnable).start() and this will cause runnable.run() to take place in a different thread. (Where runnable should be an instance of StockRunnable).

You may want to keep the instance of the thread you created to later test its state (for example, waiting for it to finish running).

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM