我的疑惑是,实现两个线程同步,必须要持有一个相同的对象吗,还有就是线程的等待和唤醒为什么要用他所持有的对象进行操作,能不能建一个本身对象然后进行操作。- public class Test{
- static int i = 1;
- public static void main(String[] args){
- Object obj = new Object();
- ThreadTwo t2 = new ThreadTwo(obj);
- ThreadOne t1 = new ThreadOne(obj,t2);
- t1.start();
- }
- }
- class ThreadOne extends Thread{
- private Object obj;
- private Thread t;
- public ThreadOne(Object obj,Thread t){
- this.obj = obj;
- this.t = t;
- }
- @Override
- public void run(){
- synchronized(obj){
- t.start();
- while(true){
- Test.i--;
- System.out.println(Test.i);
- try{
- obj.wait();
- }catch(Exception e){
- e.printStackTrace();
- }
- obj.notify();
- }
- }
- }
- }
- class ThreadTwo extends Thread{
- private Object obj;
- public ThreadTwo(Object obj){
- this.obj = obj;
- }
- @Override
- public void run(){
- synchronized(obj){
- while(true){
- Test.i++;
- System.out.println(Test.i);
- obj.notify();
- try{
- obj.wait();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码 |