Java多线程-sleep/interrupt/join/simpleExample

sleep

Thread.sleep让当前线程暂停执行一段时间,CPU时间让给其它线程和进程;sleep的时间段是不精确的;sleep可以被中断

 

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

 

interrupt

interrupt表明线程应该停止,由程序员决定如何处理这个interrupt,一般结束线程。

中断机制通过内部一个叫做interrupt status的flag来实现的,调用Thread.interrupt来设置flag,调用静态方法Thread.interrupted来检查中断状态,它会清空flag;调用非静态方法isInterrupted检查状态后不会清空flag;此外方法中捕获InterruptedException后flag也会被清空

运行下面的代码观察结果

package mthread;

public class ThreadInterrupt {

    static class InterruptThreadTest extends Thread{

        @Override
        public void run() {
            for(int i = 0; i < 4; i++) {
                try {
                    System.out.println("thread" + i);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    System.out.println("interrupt ");
                    System.out.println(" loop " + i);
                    System.out.println(Thread.interrupted());
                }
            }
        }
        
    }
    
    
    static class InterruptThreadTest1 extends Thread{

        @Override
        public void run() {
            for(int i = 0; i < 100000; i++) {
                    System.out.println("thread" + i);
                    if(Thread.interrupted()){
                        System.out.println("interrupt " + i);
                        System.out.println("interrupt " + Thread.interrupted());
                        return;
                    }
            }
        }
        
    }
    
    static class InterruptThreadTest2 extends Thread{

        @Override
        public void run() {
            for(int i = 0; i < 100000; i++) {
                    System.out.println("thread" + i);
                    if(Thread.currentThread().isInterrupted()){
                        System.out.println("interrupt " + i);
                        System.out.println("interrupt " + Thread.currentThread().isInterrupted());
                        return;
                    }
            }
        }
        
    }
    
    
    public static void main(String[] args) throws InterruptedException {
        InterruptThreadTest t = new InterruptThreadTest(); 
        t.start();
        System.out.println("sleep start");
        Thread.sleep(300);
        System.out.println("interrupt start");
        t.interrupt();
        
        /*InterruptThreadTest1 t1 =  new InterruptThreadTest1();
        t1.start();
        System.out.println("sleep start");
        Thread.sleep(10);
        System.out.println("interrupt start");
        t1.interrupt();*/
        
    }

}

 

 

join

join方法允许一个线程等待另一个线程运行完成,通过调用t.join方法来实现,这会使当前线程暂停执行,等待t的完成

package mthread;

public class ThreadJoin {
    
    static class Counter implements Runnable{

        @Override
        public void run() {
            int counter = 0;
            while(100>counter) {
                System.out.println(counter);
                counter++;
            }
        }
        
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Counter());
        t.start();
        System.out.println("wait for counter thread ");
        //comment out the following line to test again
        t.join();
        System.out.println("done");
    }

}

 

The simple Thread Example

package mthread;

public class SimpleThreads {

    // Display a message, preceded by
    // the name of the current thread
    static void threadMessage(String message) {
        String threadName =
            Thread.currentThread().getName();
        System.out.format("%s: %s%n",
                          threadName,
                          message);
    }

    private static class MessageLoop
        implements Runnable {
        public void run() {
            String importantInfo[] = {
                "Mares eat oats",
                "Does eat oats",
                "Little lambs eat ivy",
                "A kid will eat ivy too"
            };
            try {
                for (int i = 0;
                     i < importantInfo.length;
                     i++) {
                    // Pause for 4 seconds
                    Thread.sleep(4000);
                    // Print a message
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e) {
                threadMessage("I wasn't done!");
            }
        }
    }

    public static void main(String args[])
        throws InterruptedException {

        // Delay, in milliseconds before
        // we interrupt MessageLoop
        // thread (default one hour).
        //long patience = 1000 * 60 * 60;
        long patience = 1000 * 8;

        // If command line argument
        // present, gives patience
        // in seconds.
        if (args.length > 0) {
            try {
                patience = Long.parseLong(args[0]) * 1000;
            } catch (NumberFormatException e) {
                System.err.println("Argument must be an integer.");
                System.exit(1);
            }
        }

        threadMessage("Starting MessageLoop thread");
        long startTime = System.currentTimeMillis();
        Thread t = new Thread(new MessageLoop());
        t.start();

        threadMessage("Waiting for MessageLoop thread to finish");
        // loop until MessageLoop
        // thread exits
        while (t.isAlive()) {
            threadMessage("Still waiting...");
            // Wait maximum of 1 second
            // for MessageLoop thread
            // to finish.
            t.join(1000);
            if (((System.currentTimeMillis() - startTime) > patience)
                  && t.isAlive()) {
                threadMessage("Tired of waiting!");
                t.interrupt();
                // Shouldn't be long now
                // -- wait indefinitely
                t.join();
            }
        }
        threadMessage("Finally!");
    }
}

 

posted on 2014-11-06 11:58  ukouryou  阅读(210)  评论(0编辑  收藏  举报

导航