The method of JAVA threads

2010-08-22  来源:本站原创  分类:Java  人气:150 

wait (), notify (), notifyAll () and suspend (), resume (), sleep () discussion

A function of the difference between these two groups

1) wait () to the current thread into the stagnant state, occupied by the current thread will release the "lock symbol", so that the thread object in the synchronized resources can be objects in other threads; and suspend () and sleep ( ) to the current thread into the stagnant state will not release the current thread share some of the "lock symbol."

2) before a set of functions must be synchronized to call a function or synchronized block, otherwise an error when running; then a set of functions can be non-synchronized and synchronized block in the calling function.

Choice between these two sets of functions 2

Java2 has not recommended a set of functions after use. Because the call to wait () will not release the current thread made by "lock symbol" that could easily lead to "deadlock."

sleep () and wait () What is the difference? out favorite threads
sleep () method is to thread the way to stop some time. In the sleep interval expires, the thread does not immediately reinstated. This is because at that time, other threads may be running and not to give up schedule, unless (a) "wake up" the thread with higher priority (b) running thread for other reasons obstruction.
wait () is thread interactions, if the thread on a synchronization object (method) x issues a wait () call, the thread will be suspended, was transferred object (method) into the wait state, or wait until it is time to wake up.

Wait when the other thread can access the locked object (call wait, lock it and leave);
Wait method is called when the necessary locking of the object;
Methods provided by Object
Sleep is also when the other threads can not access locked objects (sleep also holding lock);
Thread provides Refer to the following two examples will all understand ......

Synchronization:
a. only one lock for each object
b. When a thread synchronization methods to access, other threads can access the object of other non-synchronized methods, but also can affect the synchronization of the internal variables.

Example 1:

Java code

  1. public class TT implements Runnable (
  2. int b = 100;
  3. public synchronized void m1 () throws Exception (
  4. b = 1000;
  5. Thread.sleep (1000);
  6. System.out.println ("b =" + b);
  7. )
  8. public synchronized void m2 () throws Exception (
  9. Thread.sleep (3000);
  10. b = 2000;
  11. )
  12. public void run () (
  13. try (
  14. m1 ();
  15. ) Catch (Exception e) (
  16. e.printStackTrace ();
  17. )
  18. )
  19. public static void main (String [] args) throws Exception (
  20. TT tt = new TT ();
  21. Thread t = new Thread (tt);
  22. t.start ();
  23. tt.m2 ();
  24. System.out.println (tt.b);
  25. )
  26. )
  27. === Output may ==== 2
  28. If the main thread lock the current object, the output is:
  29. 2000
  30. b = 1000
  31. If the child thread lock the current object, the output is:
  32. 1000
  33. b = 1000

public class TT implements Runnable {
        int b = 100;

        public synchronized void m1() throws Exception{
                b = 1000;
                Thread.sleep(1000);
                System.out.println("b = " + b);
        }

        public synchronized void m2() throws Exception {
                Thread.sleep(3000);
                b = 2000;
        }

        public void run() {
                try {
                        m1();
                } catch(Exception e) {
                        e.printStackTrace();
                }
        }

        public static void main(String[] args) throws Exception {
                TT tt = new TT();
                Thread t = new Thread(tt);
                t.start();
                tt.m2();

                System.out.println(tt.b);
        }
}

=== Output 2 may  ====
 If the main thread locks the current object, output the result as  :
2000
b = 1000
 If the child thread locks the current object, output the result as  :
1000
b = 1000

Example 2: Example Name: Producer - Consumer problem often encountered the problem how to resolve mutually exclusive was it?
A: The mutual exclusion of the two operations into a single class of two methods, and then let the two methods are coupled with synchronized keyword modification

/ * * Source File Name: SyncTest.java
* Highlights:
* 1. Shared data inconsistencies / protection of critical resources
* 2. Java object lock concept
* 3. Synchronized keyword / wait () and notify () method
* /

Java code

  1. package com.wlh;
  2. public class ProduceConsumer (
  3. public static void main (String args []) (
  4. SyncStack stack = new SyncStack ();
  5. Runnable p = new Producer (stack);
  6. Runnable c = new Consumer (stack);
  7. Thread t1 = new Thread (p);
  8. Thread t2 = new Thread (c);
  9. t1.start ();
  10. t2.start ();
  11. )
  12. )
  13. / **
  14. * Support multi-threaded implementation of synchronous operation of the stack
  15. * Only one thread can lock the current object, and synchronization lock before the implementation of the current object
  16. * In the same time, push and pop synchronization method can be only one in the implementation of
  17. * @ Author wulihai
  18. * /
  19. class SyncStack (
  20. private int index = 0;
  21. private char [] data = new char [6];
  22. public synchronized void push (char c) (
  23. if (index == data.length) (
  24. try (
  25. this. wait ();
  26. ) Catch (InterruptedException e) ()
  27. )
  28. this. notify ();
  29. data [index] = c;
  30. index + +;
  31. )
  32. public synchronized char pop () (
  33. if (index == 0) (
  34. try (
  35. this. wait ();
  36. ) Catch (InterruptedException e) ()
  37. )
  38. this. notify ();
  39. index -;
  40. return data [index];
  41. )
  42. )
  43. class Producer implements Runnable (
  44. SyncStack stack;
  45. public Producer (SyncStack s) (
  46. stack = s;
  47. )
  48. public void run () (
  49. for (int i = 0; i <20; i + +) (
  50. char c = (char) (Math.random () * 26 + 'A');//
  51. stack.push (c);
  52. System.out.println ("produced:" + c);
  53. try (
  54. Thread.sleep ((int) (Math.random () * 1000)); / / Random rest, so that seems the number of production and consumption of products are random
  55. ) Catch (InterruptedException e) (
  56. )
  57. )
  58. )
  59. )
  60. class Consumer implements Runnable (
  61. SyncStack stack;
  62. public Consumer (SyncStack s) (
  63. stack = s;
  64. )
  65. public void run () (
  66. for (int i = 0; i <20; i + +) (
  67. char c = stack.pop ();
  68. System.out.println ("consumer:" + c);
  69. try (
  70. Thread.sleep ((int) (Math.random () * 1000 ));// random breaks, so the products look the number of production and consumption are random
  71. ) Catch (InterruptedException e) (
  72. )
  73. )
  74. )
  75. )

package com.wlh;

public class ProduceConsumer {
    public static void main(String args[]){
            SyncStack stack = new SyncStack();
            Runnable p=new Producer(stack);
            Runnable c = new Consumer(stack);
            Thread t1 = new Thread(p);
            Thread t2 = new Thread(c);
            t1.start();
            t2.start();
    }
}   

  /**
   *  Supports multi-threading synchronization operation stack implementation
   *  Because only one thread can lock the current object, and the synchronization method execution before it locks the current object  ,
   *  The same time synchronization method  push And there can be only one pop under implemented
   * @author wulihai
   */
class SyncStack{
    private int index = 0;
    private char []data = new char[6];     

    public synchronized void push(char c){
        if(index == data.length){
        try{
                this.wait();
        }catch(InterruptedException e){}
        }
        this.notify();
        data[index] = c;
        index++;
    }
    public synchronized char pop(){
        if(index ==0){
            try{
                this.wait();
            }catch(InterruptedException e){}
        }
        this.notify();
        index--;
        return data[index];
    }
}   

class  Producer implements Runnable{
    SyncStack stack;
    public Producer(SyncStack s){
        stack = s;
    }
    public void run(){
        for(int i=0; i<20; i++){
            char c =(char)(Math.random()*26+'A');//
            stack.push(c);
            System.out.println("produced:"+c);
            try{
                Thread.sleep((int)(Math.random()*1000)); // Random rest looks production and consumption of the product number is random
            }catch(InterruptedException e){
            }
        }
    }
}   

class Consumer implements Runnable{
    SyncStack stack;
    public Consumer(SyncStack s){
        stack = s;
    }
    public void run(){
        for(int i=0;i<20;i++){
            char c = stack.pop();
            System.out.println(" Consumption  :"+c);
            try{
                Thread.sleep((int)(Math.random()*1000));// Random rest looks production and consumption of the product number is random
            }catch(InterruptedException e){
            }
        }
    }
}  

Deadlock: When one or more processes waiting for system resources, system resources, this process itself has also been occupied or other process

Patients: results of two threads who do not print the output data

Java code

  1. package com.wlh;
  2. public class DeadLock extends Thread (
  3. int flag = 0;
  4. static Object o1 = new Object ();
  5. static Object o2 = new Object ();
  6. public DeadLock (int flag) (
  7. this. flag = flag;
  8. )
  9. @ Override
  10. public void run () (
  11. if (this. flag == 1) (
  12. synchronized (o1) (
  13. System.out.println (Thread.currentThread (). GetName () + "lock object o1");
  14. try (
  15. Thread.sleep (1000); / / allow another thread to enter an area separate, locked object o2
  16. ) Catch (InterruptedException e) (
  17. e.printStackTrace ();
  18. )
  19. synchronized (o2) (
  20. System.out.print ("this.flag =" + this. Flag);
  21. )
  22. )
  23. )
  24. if (this. flag == 2) (
  25. synchronized (o2) (
  26. System.out.println (Thread.currentThread (). GetName () + "lock object o2");
  27. try (
  28. Thread.sleep (1000); / / allow another thread to enter an area separate, locked object o1
  29. ) Catch (InterruptedException e) (
  30. e.printStackTrace ();
  31. )
  32. synchronized (o1) (
  33. System.out.print ("this.flag =" + this. Flag);
  34. )
  35. )
  36. )
  37. )
  38. public static void main (String [] args) (
  39. DeadLock d1 = new DeadLock (1);
  40. DeadLock d2 = new DeadLock (2);
  41. d1.start ();
  42. d2.start ();
  43. )
  44. )

package com.wlh;

public class DeadLock extends Thread {

        int flag=0;
        static Object o1=new Object();
        static Object o2=new Object();

        public DeadLock(int flag){
                this.flag=flag;
        }
        @Override
        public void run() {
                if(this.flag==1){
                        synchronized(o1){
                                System.out.println(Thread.currentThread().getName()+" Lock objects  o1");
                                try {
                                        Thread.sleep(1000);// Allow another thread to enter another region, the locked object  o2
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                                synchronized(o2){
                                        System.out.print("this.flag="+this.flag);
                                }
                        }

                }
                if(this.flag==2){
                        synchronized(o2){
                                System.out.println(Thread.currentThread().getName()+" Lock objects  o2");
                                try {
                                        Thread.sleep(1000);// Allow another thread to enter another region, the locked object  o1
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                                synchronized(o1){
                                        System.out.print("this.flag="+this.flag);
                                }

                        }
                }
        }

        public  static void main(String []args){
                DeadLock d1=new DeadLock(1);
                DeadLock d2=new DeadLock(2);
                d1.start();
                d2.start();
        }
}

Join Methods: a sub-thread into the main thread, that is, all other sub-thread to run the full implementation of the complete implementation of the main thread after Example 1:

Java code

  1. package com.wlh;
  2. public class TestJoin (
  3. public static void main (String [] args) (
  4. MyThread2 t1 = new MyThread2 ("child thread");
  5. t1.start ();
  6. / * Try (
  7. t1.join ();
  8. ) Catch (InterruptedException e) () * /
  9. for (int i = 1; i <= 10; i + +) (
  10. try (
  11. Thread.sleep (1000); / / 1000 second break the current thread
  12. System.out.println ("i am main thread");
  13. ) Catch (InterruptedException e) (
  14. e.printStackTrace ();
  15. )
  16. )
  17. )
  18. )
  19. class MyThread2 extends Thread (
  20. MyThread2 (String s) (
  21. super (s);
  22. )
  23. public void run () (
  24. for (int i = 1; i <= 10; i + +) (
  25. System.out.println ("i am" + getName ());
  26. try (
  27. sleep (1000); / / 1000 second break the current thread
  28. ) Catch (InterruptedException e) (
  29. return;
  30. )
  31. )
  32. )
  33. )

package com.wlh;

public class TestJoin {
  public static void main(String[] args) {
    MyThread2 t1 = new MyThread2(" Child thread  ");
    t1.start();
     /*    try {
        t1.join();
    } catch (InterruptedException e) {}*/

    for(int i=1;i<=10;i++){
        try {
                        Thread.sleep(1000);// The current thread break 1000 seconds
                        System.out.println("i am main thread");
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }

    }
  }
}
class MyThread2 extends Thread {
  MyThread2(String s){
        super(s);
  }

  public void run(){
    for(int i =1;i<=10;i++){
      System.out.println("i am "+getName());
      try {
        sleep(1000);// The current thread break 1000 seconds
      } catch (InterruptedException e) {
        return;
      }
    }
  }
}

Note: Sub threads and main thread alternately implementation
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
i am a child thread
i am main thread
Example 2: In t1.start () sub-thread ready;, add t1.join (), the other thread t1 after the implementation of complete implementation of the main thread

Java code

  1. package com.wlh;
  2. public class TestJoin (
  3. public static void main (String [] args) (
  4. MyThread2 t1 = new MyThread2 ("child thread");
  5. t1.start ();
  6. try (
  7. t1.join ();
  8. ) Catch (InterruptedException e) ()
  9. for (int i = 1; i <= 10; i + +) (
  10. try (
  11. Thread.sleep (1000); / / 1000 second break the current thread
  12. System.out.println ("i am main thread");
  13. ) Catch (InterruptedException e) (
  14. e.printStackTrace ();
  15. )
  16. )
  17. )
  18. )
  19. class MyThread2 extends Thread (
  20. MyThread2 (String s) (
  21. super (s);
  22. )
  23. public void run () (
  24. for (int i = 1; i <= 10; i + +) (
  25. System.out.println ("i am" + getName ());
  26. try (
  27. sleep (1000); / / 1000 second break the current thread
  28. ) Catch (InterruptedException e) (
  29. return;
  30. )
  31. )
  32. )
  33. )

package com.wlh;

public class TestJoin {
  public static void main(String[] args) {
    MyThread2 t1 = new MyThread2(" Child thread  ");
    t1.start();
      try {
        t1.join();
    } catch (InterruptedException e) {}
    for(int i=1;i<=10;i++){
        try {
                        Thread.sleep(1000);// The current thread break 1000 seconds
                        System.out.println("i am main thread");
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }

    }
  }
}
class MyThread2 extends Thread {
  MyThread2(String s){
        super(s);
  }

  public void run(){
    for(int i =1;i<=10;i++){
      System.out.println("i am "+getName());
      try {
        sleep(1000);// The current thread break 1000 seconds
      } catch (InterruptedException e) {
        return;
      }
    }
  }
}

Output:

i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am a child thread
i am main thread
i am main thread
i am main thread
i am main thread
i am main thread
i am main thread
i am main thread
i am main thread
i am main thread
i am main thread

Yeild method: the current thread to the CPU execution time to the other thread for a while. Note: It is for the moment that they will be back. . .

Java code

  1. package com.wlh;
  2. public class TestYield (
  3. public static void main (String [] args) (
  4. MyThread3 t1 = new MyThread3 ("t1");
  5. MyThread3 t2 = new MyThread3 ("t2");
  6. t1.start (); t2.start ();
  7. )
  8. )
  9. class MyThread3 extends Thread (
  10. MyThread3 (String s) (super (s);)
  11. public void run () (
  12. for (int i = 1; i <= 100; i + +) (
  13. System.out.println (getName ()+": "+ i);
  14. if (i% 10 == 0) (
  15. yield ();
  16. )
  17. )
  18. )
  19. )

package com.wlh;
public class TestYield {
  public static void main(String[] args) {
    MyThread3 t1 = new MyThread3("t1");
    MyThread3 t2 = new MyThread3("t2");
    t1.start(); t2.start();
  }
}
class MyThread3 extends Thread {
  MyThread3(String s){super(s);}
  public void run(){
    for(int i =1;i<=100;i++){
      System.out.println(getName()+": "+i);
      if(i%10==0){
        yield();
      }
    }
  }
}

Output: if a thread executes an integer multiple of 10, must give up the CPU time to other threads will be the implementation of a
t1: 1
t1: 2
t1: 3
t1: 4
t1: 5
t1: 6
t1: 7
t1: 8
t1: 9
t1: 10
t2: 1
t2: 2
t2: 3
t2: 4
t2: 5
t2: 6
t2: 7
t2: 8
t2: 9
t2: 10
t1: 11
t1: 12
t1: 13
t1: 14
t1: 15
t1: 16
t1: 17
t1: 18
t1: 19
t1: 20
t2: 11
t2: 12
t2: 13
t2: 14
t2: 15
...........
..............
...................

相关文章
  • The method of JAVA threads 2010-08-22

    wait (), notify (), notifyAll () and suspend (), resume (), sleep () discussion A function of the difference between these two groups 1) wait () to the current thread into the stagnant state, occupied by the current thread will release the "lock symb

  • java threads in the Thread in the start () and run () method of the difference between (2) -- 2008-07-19

    java threads in the Thread in the start () and run () method of the difference between (2) - examples of 2009-02-10 12:38 example: class NewThread implements Runnable ( Thread t; public NewThread () ( t = new Thread (this, "Demo thread"); System

  • Simple to use Java threads Introduction 2009-03-04

    Yesterday I read an on Synchronized (thread-safe post), but feel a little strange, in fact, when you understand some basic, you can be completely self-taught Java, but the OO idea is to, through a large number of examples and practical shape. (In fac

  • Java Threads Summary 2010-04-28

    Often seen in the above forum thread helpless beginners, it summed up the following article, I hope some are learning to use java thread help beginners. First of all, the thread first need to know to understand some basic things, we are now used by m

  • Java Threads Summary (change) 2010-05-08

    In the forum thread above, I often see beginners on the helpless, so summed up the following article, I hope some are learning to use for beginners java thread help. First of all, the thread first need to know to understand some basic things, we are

  • Java threads may not use all your CPUs 2010-06-10

    Enterprise-level applications often need more CPU power than a single-CPU machine can provide, but getting applications to effectively use multiple CPUs can be tricky. If you're lucky, you may be able to run an application on separate single-CPU mach

  • java threads can be created 2010-07-09

    java threads can be created, mainly associated with the following factors: 1,32-bit or64 for the system? 2, every process in the current system the maximum addressable space. 3, the memory number of the current jvm 4, set the thread stack size-Xss 32

  • Stop Java threads, be careful interrupt () method 2009-08-10

    ---- Transfer from http://www.blogjava.net/jinfeng_wang/archive/2008/04/27/196477.html Procedures are very simple. However, programmers face, multi-threaded showing a new set of challenges, if not properly addressed, will lead to unexpected behavior

  • Java threads Study Notes (3) the background thread 2010-04-19

    The so-called background thread, is when the program runs in the background thread to provide a universal service, and this thread does not belong to an integral part of the program. So when the end of all non-background threads, the program will cea

  • Java threads Study Notes (5) Resource Sharing 2010-04-24

    IncreaseClient held in a base, from the increase each method call, return the original value, increase method from Canada twice in the check method to judge whether the return difference between value and current value of 2. multithreaded environment

  • Java threads Study Notes (8) collaboration between threads 2010-04-26

    wait () and notifyAll () Call sleep () when the lock has not been released, called yeild () is the same. When a task which met in the way of the wait () call when the thread execution is suspended, the object lock is released. Because the wait () wil

  • Java threads Learning Notes (10) CountDownLatch and CyclicBarrier 2010-04-30

    CountDownLatch: A synchronous secondary class, in the completion of a group of other threads are executed before the operation, which allows one or more threads have been waiting for. Initialized with a given count CountDownLatch. As the call countDo

  • Communication between Java threads - the callback is implemented 2010-12-15

    Callback instance method Principle: an implementation of the callback class is defined as a class interface (interface can save), then multiple threads in each class are injected into a callback object. When the thread is finished, through the callba

  • Template Method Pattern - java and the Comparable interface to sort an array of usage 2010-03-29

    1, an overview of Arrays class has a static method sort, use this method we can pass the array we want to sort into order, because we passed an array reference, so sorting through the results of the completion of this reference to change the array. For th

  • The equals method of java class 2010-03-29

    Chinese New Year is over, today, would like to ponder the next java basics to remember when suddenly encountered the problem of the equals method of rewriting, is hereby recalled record: Most of the books, teaching materials and even in the jdk's equ

  • method of java in the path taken 2010-02-15

    In order to obtain web-app directory. Properties file, you must first obtain a web-app's WEB-INF directory, online there are a lot of ways, generally described as follows: 1, java program to get System.out.println ( "1" + Thread.currentThread ()

  • Java Threads document questions 2010-03-28

    When a thread into an object of a synchronized method, other threads can access this object is the other way? An otherwise non-synchronized method, you can 2 Other methods are also synchronized method, then can not

  • Java threads Study Notes (4) thread join 2010-04-24

    "Java programming ideas," an example, if a thread in another thread t call t.join (), this thread will be suspended until the target thread t before the end of recovery. package com.woxiaoe.study.thread; /** * Test threads join * @author Small e

  • Java threads Study Notes (9) the producer consumer problem 2010-04-29

    Using multiple threads to simulate the producer consumer problem. BlockingQueue used to achieve more convenient and safer. Simulation generated a cook products, consumer spending, when the product is greater than 10 times the number of chefs rest, bu

  • Java threads Learning Notes (11) DelayQueue applications 2010-05-01

    DelayQueue Is an unbounded BlockingQueue, for the placement of a Delayed interface object, the object of which can only be in its due time removed from the queue. This queue is ordered that the team first object of the delay due the longest. Note: Th