线程笔记

来源:互联网 发布:求抢票软件 编辑:程序博客网 时间:2024/06/06 12:57
sleep()
sleep(2000)使线程休眠2秒

join()
线程A加入到线程B,A先执行,B会等待,A执行完后B再执行

interrupt()
在以前的时候会使用stop()停止线程,但是线程不安全,已经废除了。现在会用两种方法停止线程。
1.run()方法中使用无限循环,使用布尔标记控制循环停止
public class InterruptedTest implements Runnable{    private boolean isContinue=false;    public void run(){        while(true){            if (isContinue)break;        }    }    public void setContinue(){        this.isContinue = true;        }}

2.当线程进入了就绪状态(sleep或wait),可以使用interrupt()方法使线程离开run()方法,同时结束线程,但程序会抛出InterruptedException
以上是书上说的,但是通过查阅资料后发现,当捕获了这个异常之后,线程中断的状态被清除了,会变成false(中断的时候是true),所以捕获异常之后,线程还会继续
下面一段代码就能展示使用interrupt()时的状态
public class InterruptedSwing extends JFrame {    Thread thread;    public static void main(String[] args){        init(new InterruptedSwing(), 100, 100);    }    public InterruptedSwing(){        super();        final JProgressBar progressBar = new JProgressBar();        getContentPane().add(progressBar, BorderLayout.NORTH);        progressBar.setStringPainted(true);        thread = new Thread(new Runnable() {            int count = 0;            public void run() {                while(true){                    progressBar.setValue(++count);                    try {                        System.out.println("线程正在跑,进度:" + count + "     线程是否被中断:" +thread.isInterrupted());                        thread.sleep(100);                    } catch (InterruptedException e) {                        System.out.println("当线程被中断,线程是否被中断:" + thread.isInterrupted());                    }                }            }        });        thread.start();        System.out.println("线程开启后最初中断状态:" +  thread.isInterrupted());        thread.interrupt();    }    public static void init(JFrame frame, int width, int height){        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setSize(width, height);        frame.setVisible(true);    }}

结果:



setPriority()
调整线程的优先级,在1~10之内,否则会产生异常。线程的优先级数字越高,优先级越高,若AB线程为同一优先级,A线程会先得到一小段CPU时间片运行,时间结束后,换B得到时间片运行,(如此交替运行),直到两个线程都运行结束

synchronized(Object){}
线程同步。将资源放在了同步块中,Object为任意一个对象,这个对象有一个标志位,0状态表示有线程在运行,其他线程就处于就绪状态,结束之后标志位变为1,其他线程才能执行,并将标志位继续变为0。
synchronized还可以作为关键字修饰方法,作为同步方法。 synchronized void f(){}

wait()
wait()是线程进入就绪状态,无限的等待下去。
wait(2000)在2秒内暂停,与sleep(2000)类似,不同的是sleep()不释放锁,wait()释放锁

notify()
notifyAll()

唤醒线程

注:wait()与notify()、notifyAll()只能在同步块或同步方法中使用