Java多线程
java进程是一个任务的动态执行过程,线程是比进程更小的执行单位,如果把进程比作一个班级的话,那么线程就是班级里面的每一位学生。
线程常用的实现方式为继承Thread类和实现runnable接口。
Thread常用的方法如下:
线程启动的步骤:
1,类继承Thread类或者是继承了Runnable接口;
2,new一个线程;
3,.start()开启一个线程;
例:
package com.pamguangyou.concurrent;
public class Actor extends Thread{
public void run(){
System.out.println(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("佐酒先生");
actor.start();
Thread actressthread=new Thread(new Actress(),"潘掌柜");
actressthread.start();
Thread actressthread2=new Thread(new Actress2(),"潘先生");
actressthread2.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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName()+"演出结束了!");
}
}
我们不光要知道怎么正确的启动线程,
还要知道怎么去停止线程。
stop()方法不是正确的停止线程的方法。
正确的停止线程的方法可以采用boolean的ture和false搭配while来控制,ture时执行线程,false时停止线程。
线程之间的交互:争用条件,同步与互斥
同步与互斥也是线程之间的交互。