Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.webanimal.academy_lesson04_threads;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- public class MainActivity extends AppCompatActivity {
- //==============================================================================================
- // Static
- //==============================================================================================
- private static final int FPS_LIMIT = 240;
- //==============================================================================================
- // Fields
- //==============================================================================================
- private Thread tOne;
- private Thread tTwo;
- private final ThreadSwitch ts = new ThreadSwitch();
- private boolean isRunning = true;
- //==============================================================================================
- // Activity callbacks
- //==============================================================================================
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- createThreads();
- }
- @Override
- protected void onStart() {
- super.onStart();
- startThreads();
- }
- @Override
- protected void onStop() {
- stopThreads();
- super.onStop();
- }
- //==============================================================================================
- // Private methods
- //==============================================================================================
- private class LeftLeg implements Runnable {
- @Override
- public void run() {
- int fps = 0;
- while (isRunning) {
- if (fps > FPS_LIMIT) {
- synchronized (ts) {
- if (ts.get() % 2 == 0) {
- System.out.println("Left step");
- ts.raise(); // 0 ---> 1
- }
- fps = 0;
- }
- }
- fps++;
- }
- }
- }
- private class RightLeg implements Runnable {
- @Override
- public void run() {
- int fps = 0;
- while (isRunning) {
- if (fps > FPS_LIMIT) {
- synchronized (ts) {
- if (ts.get() % 2 != 0) {
- System.out.println("Right step");
- ts.clear(); // 1 ---> 0
- }
- fps = 0;
- }
- }
- fps++;
- }
- }
- }
- private void createThreads() {
- if (tOne == null) {
- tOne = new Thread(new LeftLeg());
- }
- if (tTwo == null) {
- tTwo = new Thread(new RightLeg());
- }
- }
- private void startThreads() {
- synchronized (ts) {
- ts.clear(); // Always LeftLeg is first on start
- }
- isRunning = true;
- if (tOne != null && (!tOne.isAlive() || tOne.isInterrupted())) {
- tOne.start();
- }
- if (tTwo != null && (!tTwo.isAlive() || tTwo.isInterrupted())) {
- tTwo.start();
- }
- }
- private void stopThreads() {
- isRunning = false;
- if (tOne != null && (tOne.isAlive() || !tOne.isInterrupted())) {
- tOne.interrupt();
- }
- if (tTwo != null && (tTwo.isAlive() || !tTwo.isInterrupted())) {
- tTwo.interrupt();
- }
- }
- }
Add Comment
Please, Sign In to add comment