/**
进程
程序(任务)的执行过程
持有资源(共享文件、共享内存)和线程
try{
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println(e);
}
*/
public class ThreadDemo{
public static void main(String[] args){
//线程创建的第一种方法:继承Thread 类
/*
Actor actor = new Actor();
actor.setName("Mr.Thread");
actor.start();
//线程创建的第二种方法:实现Runnable接口
Thread actress = new Thread(new Actress(),"Mr.Runnable");
actress.start();
*/
new Stag().start();
}
}
/*-------分割线----------------------------------*/
//舞台
class Stag extends Thread{
public void run(){
ArmyRunnable army1 = new ArmyRunnable();
ArmyRunnable army2 = new ArmyRunnable();
Thread t1 = new Thread(army1,"共军");
Thread t2 = new Thread(army2,"国军");
//启动线程
t1.start();
t2.start();
//舞台休眠一段时间【作用是使主线程休眠,跑t1和t2线程】
try{
Thread.sleep(100);
}catch(InterruptedException e){
System.out.println(e);
}
System.out.println("半路杀出一个程咬金");
Thread keyPerson = new KeyPerson();
keyPerson.setName("程咬金");
System.out.println("程咬金是来结束战斗的");
//停止线程
army1.flag = false;
army2.flag = false;
try{
Thread.sleep(2000);
System.out.println("中场休息2000");
}catch(InterruptedException e){
System.out.println(e);
}
//历史大戏留个关键人物
keyPerson.start();
/*
try{
keyPerson.join();
}catch(InterruptedException e){
System.out.println(e);
}
*/
try{
//join()的作用是:“等待该线程终止”,这里需要理解的就是该线程是指的主线程等待子线程的终止。
keyPerson.join();
}catch(InterruptedException e){
System.out.println(e);
}
System.out.println("战争结束了");
}
}
//关键人物
class KeyPerson extends Thread{
public void run(){
System.out.println(getName()+"进入战斗状态");
//战斗次数
int count = 10;
for(int i = 0;i < count;i ++){
System.out.println(Thread.currentThread().getName()+"正在大杀特杀:"+i);
}
System.out.println(getName()+"战斗结束");
}
}
//军队线程,模拟作战双方的行为
class ArmyRunnable implements Runnable{
volatile boolean flag = true;
@Override
public void run(){
//volatile 保证了线程可以正确的读取其他线程写入的值
//发动攻击次数
int count = 5;
while(flag){
for(int i = 0;i < count;i ++){
System.out.println(Thread.currentThread().getName()+"攻击对方:"+i);
//yield(),让出处理器时间(资源),然后重新竞争
Thread.yield();
}
}
}
}
class Actor extends Thread{
public void run(){
//当前线程的名称getName()
System.out.println(getName()+"是一个好演员");
int count = 0;
boolean flag = true;
while(flag){
System.out.println(getName()+"登台演出"+(++count)+"次");
if(count >= 10){
flag = false;
}
if(count%3 == 0){
try{
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println(e);
}
}
}
System.out.println(getName()+"演出结束");
}
}
class Actress implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName()+"是一个好演员");
int count = 0;
boolean flag = true;
while(flag){
System.out.println(Thread.currentThread().getName()+"登台演出"+(++count)+"次");
if(count >= 10){
flag = false;
}
if(count%3 == 0){
try{
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println(e);
}
}
}
System.out.println(Thread.currentThread().getName()+"演出结束");
}
}