多线程【慕课网】
进程的概念:
进程是程序的执行过程,它持有资源跟线程,线程是程序中最小的执行单元,同一个进程中有多个线程,线程共享进程的资源,线程之间有交互,竞争等相互作用。
线程中常用方法介绍:
实现线程有两种方法,一种是继承Thread类,另一个是实现Runnable接口,他两个都属于java.lang包,
Thread实现线程有个方法介绍:
线程简单实现代码:
package com.wyw; public class ThreadTest { public static void main(String[] args) { Thread actor = new Actor(); actor.setName("actor先生"); actor.start(); Thread actrss = new Thread(new Actrss(),"Actrss"); actrss.start(); } } class Actor extends Thread { @Override public void run() { System.out.println(getName() + "是一个演员"); /**用来计数运行次数*/ int count = 0; boolean keepRunning = true; while(keepRunning){ System.out.println(getName() + "登台演出了:" + (++count) + "次。"); if (count%10==0){ try { Actor.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println(getName() + "演出结束了"); } } class Actrss 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%10==0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println(Thread.currentThread().getName() + "演出结束了"); } }