第一部分:基础理解

1.进程由n个线程组成。线程是进程的最小单位

2.线程之间的关系:互斥、同步

3.基础:  java.lang包:Thread类(class)和Runnable接口(interface)

    Thread和Runnable之间有个共通的方法:public void run().

4.实际工作执行的方法:

多线程基础

5.当一个线程结束或者休眠,另一个线程才会运行

附上代码:

package XianCheng.com.imooc.concurrent;

public class Actor extends Thread{

    public void run(){
        System.out.println(getName()+"是一个演员");//getName()获得当前线程名称

        int count = 0;
        boolean keepRunning = true;
        while (keepRunning){
            System.out.println(getName()+"登台演出"+(++count));

            if (count == 100){
                keepRunning = false;
            }
            if (count%10 == 0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }


        System.out.println(getName()+"演出结束了");
    }

    public static void main(String[] args) {
    Thread actor = new Actor();
    actor.setName("Thread");

    actor.start();

    Thread actressThread = new Thread(new Actress(),"Runnable");
    actressThread.start();
    }
    //当一个线程休眠或者结束时,另一个线程才会运行

}

class Actress implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"是一个演员");

        int count = 0;
        boolean keepRunning = true;
        while (keepRunning){
            System.out.println(Thread.currentThread().getName()+"登台演出"+(++count));

            if (count == 100){
                keepRunning = false;
            }
            if (count%10 == 0){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }


        System.out.println(Thread.currentThread().getName()+"演出结束了");
    }
}

第二部分:实战开发




相关文章:

  • 2022-02-05
猜你喜欢
  • 2021-12-25
  • 2021-12-19
相关资源
相似解决方案