好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java线程等待用法实例分析

本文实例讲述了java 线程等待 用法。分享给大家供大家参考,具体如下:

线程等待

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

public class hello {

   public static void main(string[] args) {

     a a = new a();

     new thread( new myrun(a)).start();

     new thread( new myrun1(a)).start();

   }

}

class myrun implements runnable {

   private a a;

   public myrun(a a) {

     this .a = a;

   }

   @override

   public void run() {

     synchronized (a) {

       a.settitle( "hello" );

       try {

         a.wait();

       } catch (interruptedexception e) {

         e.printstacktrace();

       }

       a.setnumber( 12 );

       system.out.println(a);

     }

   }

}

class myrun1 implements runnable {

   private a a;

   public myrun1(a a) {

     this .a = a;

   }

   @override

   public void run() {

     synchronized (a) {

       a.settitle( "world" );

       a.setnumber( 24 );

       a.notifyall();

       system.out.println(a);

     }

   }

}

class a {

   private string title;

   private integer number;

   public string gettitle() {

     return title;

   }

   public void settitle(string title) {

     this .title = title;

   }

   public integer getnumber() {

     return number;

   }

   public void setnumber(integer number) {

     this .number = number;

   }

   @override

   public string tostring() {

     return "a{" +

         "title='" + title + '\ '' +

         ", number=" + number +

         '}' ;

   }

}

运行输出:

a{title='world', number=24}
a{title='world', number=12}

线程等待, obj.wait() ,会释放当前的锁,对象的普通方法, obj.wait(超时时间) ,表示指定时间后可以自动唤醒

线程唤醒, obj.notify() ,唤醒一个线程, obj.notifyall() ,唤醒所以线程,obj需要和线程等待的对象一致。

wait和sleep的区别

个人认为:sleep就是一种延缓代码执行的方法,wait是有关多线程的一些高级操作。

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/shuair/article/details/81943569

查看更多关于Java线程等待用法实例分析的详细内容...

  阅读:41次