package fengke.thread; |
/** |
* Thread与Runnable基本使用 |
* |
* @author 锋客 |
* 内容: |
* 1.线程的基本行为,与运行特点 |
* 2.创建线程:一个是继承Thread,一个是实现接口Runnable |
* 3.线程的休眠 |
* 4.线程的停止最好不使用Stop(); |
*/ |
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 > 1000 ) |
keepRunning = false ; |
// 线程休眠 |
if (count % 10 == 0 ) { |
try { |
Thread.sleep( 2000 ); |
} catch (InterruptedException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} |
} |
} |
System.out.println(getName() + "的演出结束了" ); |
} |
public static void main(String[] args) { |
Thread actor = new Actor(); |
actor.setName( "Mr.Thread" ); |
actor.start(); |
Thread actressThread= new Thread( new Actress(), "Ms.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 > 1000 ) |
keepRunning = false ; |
// 线程休眠 |
if (count % 10 == 0 ) { |
try { |
Thread.sleep( 2000 ); |
} catch (InterruptedException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} |
} |
} |
System.out.println(Thread.currentThread().getName() + "的演出结束了" ); |
} |
} |