java多线程挂起

class  NewThread  implements  Runnable {
    String name;
    Thread t;
    
boolean suspendFlag;
    
    NewThread(String threadName)
{
        name 
= threadName;
        t
=new Thread(this,name);
        System.out.println(
"New Thread:" + name);
        suspendFlag
=false;
        t.start();
    }

    
    
public void run(){
        
try {
            
for(int i=15;i>0;i--){
                System.out.println( name 
+ ":" + i);
                Thread.sleep(
200);
                
synchronized(this){
                    
while(suspendFlag){
                        wait();
                    }

                }

                
            }

        }
 catch (InterruptedException e) {
            System.out.println( name 
+ " thread interrupted.");
            e.printStackTrace();
        }

        
        System.out.println( name 
+ " exiting.");
    }

    
    
public void mysuspend(){
        suspendFlag
=true;
    }

    
    
public void myresume(){
        suspendFlag
=false;
        notify();
    }

}

class  PcSleep  {

    
public static void main(String[] args) {
        NewThread obj1
=new NewThread("ONE");
        NewThread obj2
=new NewThread("TWO");

        
try {
            Thread.sleep(
1000);
            obj1.mysuspend();
            
//obj1.t.suspend();
            System.out.println( "Suspend thread one.");
            
            Thread.sleep(
1000);
            obj1.myresume();
            
//obj1.t.resume();
            System.out.println( "Resume  thread one.");
            
            obj2.mysuspend();
            
//obj2.t.suspend();
            System.out.println( "Suspend thread two.");
            
            Thread.sleep(
1000);
            obj2.myresume();
            
//obj2.t.resume();
            System.out.println( "Resume  thread two.");
            
        }
 catch (InterruptedException e) {
            System.out.println( 
"Main thread interrupted.");
            e.printStackTrace();
        }

        
        
try {
            System.out.println( 
"Waiting thread finish.");
            obj1.t.join();
            obj2.t.join();
        }
 catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        
        System.out.println( 
"Main thread exiting.");
    }

}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值