夜光序言:
黑暗中,柔和的灯光刺痛了双眼,才清楚所有的留恋不过是自己的一厢情愿。听着一首不属于自己的歌,走着一条不属于自己的路。说不尽的忧伤,走不完的辛酸。
正文: 线程的常用方法
(2)isAlive()—判断线程是否启动
// 夜光
public class TestSleep extends Thread
{
public void run()
{
for (int i = 0; i < 20; i++)
{
if (i % 10 == 0)
{
System.out.println("-------" + i);
}
System.out.print(i);
try
{
Thread.sleep(1000);
System.out.print(" 夜光: 线程睡眠1秒!\n");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new TestSleep().start();
}
}
// 夜光
public class ThreadYieldDemo
{
public static void main(String[] args)
{
System.out.println("当前的线程是"+Thread.currentThread().getName());
Thread thread1=new Thread(new YieldThread());
thread1.start();
Thread thread2=new Thread(new YieldThread());
thread2.start();
}
}
class YieldThread implements Runnable
{
public void run()
{ for(int i=1;i<=10;i++)
{ System.out.println(Thread.currentThread().getName()+"运行了"+i+"次");
if(i==5) // 夜光:当前正在执行的线程让步给其它线程
{ Thread.currentThread().yield();
}
}
}
}
// 夜光
public class TestInterrupt{
public static void main(String args[]){
ClassRoom room=new ClassRoom();
room.student.start();
room.teacher.start();
}
}
class ClassRoom implements Runnable{
Thread student,teacher; //教室里有student和teacher两个线程
ClassRoom(){
teacher=new Thread(this);
student=new Thread(this);
teacher.setName("唐三老师");
student.setName("A");
}
public void run(){
if (Thread.currentThread()==student) {
try{ System.out.println(student.getName()+"正在睡觉,不听课");
Thread.sleep(1000*60*60);
}
catch(InterruptedException e) {
System.out.println(student.getName()+"被老师叫醒了");
}
System.out.println(student.getName()+"开始听课");
}
else if(Thread.currentThread()==teacher){
for(int i=1;i<=3;i++){
System.out.println("上课!");
try {Thread.sleep(500);}
catch(InterruptedException e) {}
}
student.interrupt(); //吵醒(中断)student
}
}
}