Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. # **一、主线程向子线程传值** #
  2. 这里的值:包括基本数据类型和引用数据类型
  3. 通过构造函数实现传值的
  4. ```public class Test {
  5. public static void main(String[] args){
  6. Object obj = new Object();
  7. UserT1 ut = new UserT1(obj);
  8. ut.start();
  9. }
  10. }
  11. public class UserT1 extends Thread {
  12. Object obj;
  13. public UserT1(Object obj) {
  14. this.obj = obj;
  15. }
  16. public void run(){}
  17. ```
  18. # **二、子线程向主线程传值** #
  19. 子线程与主线程通过wait(),notify()方法传值
  20. 注:wait()和notify()方法只能从synchronized方法或块中调用,主线程与子线程必须持有【同一对象】的锁
  21. ```public class Test {
  22. public static void main(String[] args) {
  23. Object obj = new Object();
  24. UserT1 t1 = new UserT1(obj);
  25. t1.start();
  26. int a=10;
  27. synchronized (obj)
  28. {
  29. try
  30. {
  31. //等待子线程通知[必须持有同一个对象的锁],继续向下运行代码
  32. //当前运行的线程持有obj对象的锁,
  33. //在此被阻塞
  34. obj.wait();
  35. System.out.println(Thread.currentThread().getName()+","+(t1.getSum()+a));
  36. } catch (InterruptedException e)
  37. {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41. }
  42.  
  43. }
  44. }
  45.  
  46. public class UserT1 extends Thread {
  47.  
  48. int sum = 0;
  49. Object obj;
  50.  
  51. public UserT1(Object obj) {
  52. this.obj = obj;
  53. }
  54.  
  55. public void run() {
  56. synchronized (obj) {
  57. for (int i = 0; i <= 100; i++) {
  58. sum += i;
  59. }
  60. System.out.println(Thread.currentThread().getName() + "计算好了,通知主线程解锁..." + sum);
  61. //通知持有当前对象(obj)的被阻塞的线程解锁
  62. obj.notify();
  63. }
  64. }
  65. public int getSum() {
  66. return this.sum;
  67. }
  68. }
  69. ```
  70. # **三、子线程与子线程传值** #
  71. 同上,也是通过wait(),notify(),方法传值的,wait()和notify()方法只能从synchronized方法或块中调用
  72. 注:notify和notifyAll之间的关键区别在于notify()只会唤醒一个线程,而notifyAll()方法将唤醒所有线程。
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement