java note 8:synchronization

/**
 * instruction of project
 *
 * @author Aruiea.com
 * @ClassName Day07
 * @Version 1.0
 * @Date 2020/7/6 16:49
 * 线程同步:Callable(有返回值,run没有)    timeerTask
 * provider-consumer
 */
public class Day07 {

    //线程同步:Callable(有返回值,run没有)    timeerTask计时任务。
    public static void main(String[] args) throws ExecutionException, InterruptedException, ParseException {
        System.out.println("------------------------------!main!---------------------------------------");

        // future用于接收Callable返回的对象
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        Future future = threadPool.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return 123;
            }
        });

        System.out.println(future.get());

        //futureTask can be used to get return from callable or runnalbe,value.
        FutureTask futureTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                return "www.cctv.com";
            }
        });
        threadPool.submit(futureTask);
        System.out.println(futureTask.get()+".append string to end of it");

        threadPool.shutdown();

        //terminate thread
        Thread t = new Thread();
        t.start();
        t.interrupt();//can not terminate thread.only blocked

        //Timer()
        Timer timer = new Timer();

        //Schedule
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Calendar.getInstance().getTime().getSeconds());//code to execute
            }
        },new Date(),1000);//per 1000ms execute once,from when

        //yield(),join(),wait(),notify(),notifyAll(),sleep()
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.yield();//if there are another thread with same priority or higher,yield to execute other thread
                for (int i = 0; i < 10; i++) {
                    System.out.println("线程1");
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run(){
            for(int j = 0; j < 10; j++) {
                System.out.println("线程2");
            }
        }});

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    t1.join();//t1 insert here,t3 will be executed behind t1 was done
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int j = 0; j < 10; j++) {
                    System.out.println("线程3");
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();

        t1.interrupt();//set t1 to interrupt state
        System.out.println(t1.isInterrupted()+":是中断的!");//is interrupted?if no,set it to uninterrupted
        System.out.println(t1.isInterrupted()+":不是中断的!");//print,uninterrupted

        //provider-consumer model   lock where security may occur:synchronized or Lock/unLock
        new Day07().Consumer_Provider();

    }

    //provider-consumer model   lock where security may occur:synchronized or Lock/unLock
    private int goods = 10;
    private void Consumer_Provider(){
        Thread t4 = new Thread(new newThread());
        Thread t5 = new Thread(new newThread());
        t4.start();
        t5.start();
    }

    //a thread to sale goods.Inner Class
    private class newThread extends Thread{
            @Override
            public void run () {
                //synchronized symbol
                while (true) {
                    //it is neccessary to judging goods quantity into synchronized block
                    //beacuse thread outside had take up(occupy) a backup from goods.therefore,its not insecure(safe).
                    synchronized (newThread.class){
                        if (goods > 0 ){
                            System.out.println(Thread.currentThread().getName() + "售出了一件商品!" + "还剩" + goods + "件商品!");
                            goods--;

                            //prority man take some goods away      ...run away faster like  tortoise rabbit...
                            this.LockMethodTest();

                        }else {
                            System.out.println("票已售完!");
                            break;
                        }
                }

            }
        }

        //Lock/ReentrantLock:defined with global
        private Lock lock = new ReentrantLock();
        private void LockMethodTest() {
            lock.lock();
            //statement block:for avoid issue by catch exception caused programe teminate,try{}finnaly will be useful.
            // useful  helpful  
            while (true) {
                try {
                    //essential satement
                    if (goods > 0) {
                        if (goods <= 5) {
                            break;
                        }
                        System.out.println("priority 1:I will take some goods:gn" + goods + "!");
                        goods--;
                    }
                }finally{
                    lock.unlock();
                }
            }

        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值