JAVA第九周作业&实验七

学习关于多线程的内容:

自己自学所敲的代码:同步的俩种方法,我这用的是同步代码块的方法!

package com.itcast.abj.demo01;

public class MyThread implements Runnable {
    private int ticket=1000;

    @Override
    public void run() {
        for (int i = 0; i <10000 ; i++) {
            synchronized (this){//同步代码块
                if(ticket>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("卖票:ticket="+ticket--);
                }
            }

        }

    }
}

测试:

package com.itcast.abj.demo01;

public class Demo01 {
    public static void main(String[] args) {
        MyThread myThread=new MyThread();

        Thread t1=new Thread(myThread);
        Thread t2=new Thread(myThread);
        Thread t3=new Thread(myThread);
        Thread t4=new Thread(myThread);
        Thread t5=new Thread(myThread);
        Thread t6=new Thread(myThread);
        Thread t7=new Thread(myThread);
        Thread t8=new Thread(myThread);
        Thread t9=new Thread(myThread);
        Thread t10=new Thread(myThread);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();
    }

 

posted @ 2019-10-25 18:17  MIXIkikyo  阅读(163)  评论(0编辑  收藏  举报