线程的应用
1、创建线程使用继承Thread类,或实现Runnable接口,重写其中的run方法;
2、使用start()方法启动线程
3、使用voilate来访问线程中的变量,并且进行值改变;
4、使用sleep()方法来进行线程的等待延时操作;
5、使用yield()方法来结束当前线程,并且重新开始另一个线程?
6、使用join()方法,结束当前线程后再执行后续的操作
public class Stage extends Thread{
public void run(){
System.out.println("开场前……");
Army1 a = new Army1();
Army1 b = new Army1();
Thread army1 = new Thread(a,"Army1");
Thread army2 = new Thread(b,"Army2");
System.out.println("表演中……");
army1.start();
army2.start();
try {
sleep(3000);
} catch (Exception e) {
// TODO: handle exception
}
//军队结束进攻
a.con =false;
b.con =false;
try {
sleep(3000);
System.out.println("关键人物出场……");
} catch (Exception e) {
e.printStackTrace();
}
Thread thread = new Keyperson();
thread.setName("keyPerson");
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束演出");
}
public static void main(String[] args) {
Thread thread =new Stage();
thread.start();
}
}
class Army1 implements Runnable{
volatile boolean con = true;
@Override
public void run(){
while(con){
for(int i=0;i<30;i++){
System.err.println(Thread.currentThread().getName()+"开始了演出……");
Thread.yield();
if(i%10==0){
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
class Keyperson extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println(getName()+"演出中…");
}
}
}