Java多线程

来源:互联网 发布:js 算法 编辑:程序博客网 时间:2024/06/06 03:58

线程的实现

继承Thread(这种方式必须重写run()方法)如下:

public class MyThread extends Thread{
    private String name;
    public MyThread(String name){
        this.name=name;
    }
    public void run(){
        for (int i = 0; i < 10; i++) {
            System.out.println(name+":"+i);
        }
        super.run();
    }
}

实现Runnable接口;如下

public class MyThreads implements Runnable{
    private String name;
    public MyThreads(String name){
        this.name=name;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name+":"+i);
        }
    }
}

线程的状态

创建状态:准备好一个多线程对象

就绪状态:调用了start()方法,等待CPU进行调度

运行状态:执行RUN方法

阻塞状态:暂时停止执行,可将资源交给其他线程使用

终止状态:线程销毁

线程的常用方法

getName()取得线程的名称

currentThread() 取得当前线程对象

isAlive()判断当前线程是否启动

join() 强行执行当前线程

sleep()让当前线程休眠

yield()线程的礼让

线程的优先级

优先级会提高当前线程的首次执行速度,但是不一定能抢到,是一个可能性的状态

线程的同步

参考做了一个简单的同步买车票的行为,代码如下:

class Test05 implements Runnable{
        private int ticket=5;
        @Override
        public void run() {
            call();
        }
    public synchronized void call(){
        for (int i = 0; i < 10; i++) {
            if(ticket>0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("买出车票"+ticket--);
            }
        }
    }    
}    
public class SynTest{
        public static void main(String[] args) {
            Test05 ti=new Test05();
            Thread t1=new Thread(ti);
            Thread t2=new Thread(ti);
            Thread t3=new Thread(ti);
            t1.start();
            t2.start();
            t3.start();
        }
}

以上表示5张车票3个窗口买票;如果不给车票加同步,就会导致卖出第六张票的情况;这里也就是说车票资源必须共享


0 0
原创粉丝点击