Java 多线程(一)

来源:互联网 发布:js如何理解面向对象 编辑:程序博客网 时间:2024/05/06 07:27
public class Test1Thread extends Thread {    private int ticketscount = 100;    @Override    public void run() {            while (true) {            sale();            }    }    //lock    private synchronized void sale(){        if (ticketscount > 0) {            try {                //sleep                Thread.sleep(1000);                //wakeup                //Thread.interrupted();            } catch (Exception e) {                e.printStackTrace();            }            int curent = ticketscount--;            System.out.println(String.format("%s卖出了第%s张票",                    Thread.currentThread().getName(), curent));        }    }}
public class TestRunable implements Runnable {    private int ticketscount = 100;    private Lock lock = new ReentrantLock();    @Override    public void run() {        while (true){            sale();        }    }    private void sale(){        try {            lock.lock();            if(ticketscount>0){                Thread.sleep(1000);                System.out.println(String.format("%s卖出了第%s张票",                        Thread.currentThread().getName(),ticketscount--));            }        }catch (Exception e){            e.printStackTrace();        }finally {            lock.unlock();        }    }}
public class TestMain {    /**     * 对于java程序,只要有一个前台线程在运行,这个进程就不会结束     * 如果只有后台线程运行,进程会结束     */    public static void test1(){        //创建一个资源对象       Test1Thread test1Thread = new Test1Thread();        //创建多个线程来竞争资源        //线程一       Thread thread1 = new Thread(test1Thread);       thread1.setName("John");        //前台线程        thread1.setDaemon(false);      thread1.start();        //线程二        Thread thread2 = new Thread(test1Thread);        //前台线程        thread2.setDaemon(false);        thread2.setName("BOB");        thread2.start();    }    public static void test2(){        TestRunable runable = new TestRunable();        new Thread(runable).start();        new Thread(runable).start();    }    public static void main(String[] args){      // test1();       test2();    }}
原创粉丝点击