MultiThreading issues while programing for android

后端 未结 4 566
名媛妹妹
名媛妹妹 2020-12-06 04:11

I am developing on Android but the question might be just as valid on any other Java platform.

I have developed a multi-threaded app. Lets say I have a first class t

4条回答
  •  悲&欢浪女
    2020-12-06 04:25

    In ordinary Java, you would do this:

    class MyTask implements Runnable {
        void run() {
           for (int i = 0; i < Integer.MAX; i++) {
              if (i = Integer.MAX -1) {
                  System.out.println("done");
              }
           }
        }
    }
    
    
    class MyMain {
        public static void main(String[] argv) {
            for (int i = 0; i < 10; i++) {
               Thread t = new Thread(new MyTask());
               t.start();
            }
            System.out.println("bye");
        }
    }
    

    ... that kicks off 10 threads. Notice that if you accidentally invoke t.run() instead of t.start(), your runnable executes in the main thread. Probably you'll see 'bye' printed before 10 'done'. Notice that the threads 'stop' when the the run() method of the Runnable you gave to them finishes.

    I hope that helps you get your head around what it is you've got to co-ordinate.

    The tricky part with concurrency is getting threads to communicate with each other or share access to objects.

    I believe Android provides some mechanism for this in the form of the Handler which is described in the developer guide under designing for responsiveness.

    An excellent book on the subject of concurrency in Java is Java Concurency in Practice.

提交回复
热议问题