Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # **一、主线程向子线程传值** #
- 这里的值:包括基本数据类型和引用数据类型
- 通过构造函数实现传值的
- ```public class Test {
- public static void main(String[] args){
- Object obj = new Object();
- UserT1 ut = new UserT1(obj);
- ut.start();
- }
- }
- public class UserT1 extends Thread {
- Object obj;
- public UserT1(Object obj) {
- this.obj = obj;
- }
- public void run(){}
- ```
- # **二、子线程向主线程传值** #
- 子线程与主线程通过wait(),notify()方法传值
- 注:wait()和notify()方法只能从synchronized方法或块中调用,主线程与子线程必须持有【同一对象】的锁
- ```public class Test {
- public static void main(String[] args) {
- Object obj = new Object();
- UserT1 t1 = new UserT1(obj);
- t1.start();
- int a=10;
- synchronized (obj)
- {
- try
- {
- //等待子线程通知[必须持有同一个对象的锁],继续向下运行代码
- //当前运行的线程持有obj对象的锁,
- //在此被阻塞
- obj.wait();
- System.out.println(Thread.currentThread().getName()+","+(t1.getSum()+a));
- } catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- public class UserT1 extends Thread {
- int sum = 0;
- Object obj;
- public UserT1(Object obj) {
- this.obj = obj;
- }
- public void run() {
- synchronized (obj) {
- for (int i = 0; i <= 100; i++) {
- sum += i;
- }
- System.out.println(Thread.currentThread().getName() + "计算好了,通知主线程解锁..." + sum);
- //通知持有当前对象(obj)的被阻塞的线程解锁
- obj.notify();
- }
- }
- public int getSum() {
- return this.sum;
- }
- }
- ```
- # **三、子线程与子线程传值** #
- 同上,也是通过wait(),notify(),方法传值的,wait()和notify()方法只能从synchronized方法或块中调用
- 注:notify和notifyAll之间的关键区别在于notify()只会唤醒一个线程,而notifyAll()方法将唤醒所有线程。
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement