Вопрос

I have attempted to follow the examples that I have found on implementing a runnable thread, but for some reason the code is skipped.

For the sake of having a better understanding, can someone tell me what is preventing the thread code from executing?

MainActivity.java:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        String textinfo = "";

        getMenuInflater().inflate(R.menu.main, menu);
        TextView tv = (TextView) findViewById(R.id.infotext);
        textinfo += "Testing Android Runnable Thread.\n";
        tv.setText(textinfo);

        Runnable runnable = new Runnable() {
            public void run() {

                Global.classtext += "Running in thread!\n";

                long endTime = System.currentTimeMillis() + 20 * 1000;

                while (System.currentTimeMillis() < endTime) {
                    synchronized (this) {
                        try {
                            wait(endTime - System.currentTimeMillis());
                        } catch (Exception e) {
                        }
                    }

                }
            }
        };

        Thread mythread = new Thread(runnable);
        mythread.start();

        textinfo += Global.classtext;
        textinfo += "Finished.\n";
        tv.setText(textinfo);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }
}

fragment_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
     >

    <TextView
        android:id="@+id/infotext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/infotext" />
</LinearLayout>

strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Andorid Thread Test</string>
    <string name="action_settings">Settings</string>
    <string name="infotext">Android Thread Test</string>
</resources>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.apollo.androidThreadtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.apollo.androidmysqltest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The code doesn't produce any errors. It runs on the android with the output:

Testing Androd Runnable Thread. Finished.

The lines in the thread ("Running in thread!") never displays and debug shows the whole block is skipped.

Это было полезно?

Решение

Since you are running a different thread, you cannot expect the code to execute sequentially like:

        Thread mythread = new Thread(runnable);
        mythread.start();

        textinfo += Global.classtext;
        textinfo += "Finished.\n";
        tv.setText(textinfo);

        return true;

By the time the main thread hits return true, Global.classtext may have not been changed by the parallel thread yet

To see what I mean, try changing your code to this:

            Thread mythread = new Thread(runnable);
            mythread.start();

            while(mythread.isAlive()){
                //wait till thread finishes
            }

            textinfo += Global.classtext;
            textinfo += "Finished.\n";
            tv.setText(textinfo);

            return true;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top