这节课我们来讲讲线程常用的方法,还是看API文档加写代码演示:
以下是Thread类的常用方法
以下是Object类中和线程有关的方法:
Demo:
public class ThreadMethodTeach {
public static void main(String[] args) throws InterruptedException {
/**
* Thread.getName()方法不允许重写,因为返回值类型为final
* 注意:
* 如果在一个类声明前加final,则这个类无法被继承,比如java.lang.String
* 如果一个方法的返回值类型加上final,则这个方法不可以被重写
*/
/**
* Thread.getName() 获取线程的名称
* Thread.getPriority() 获取线程的优先级
* Thread.join() 停止运行当前正在运行的线程(称为线程1吧),将CPU资源让给调用join()方法的线程(称为线程2吧),
* 待线程2运行完进入停止状态后继续运行线程1
* Thread.yield() 本线程让出CPU资源,进入就绪状态
* Object.wait() 这个wait()方法是让当前正在运行的线程进入等待状态,且本对象监视这个线程
* Object.notify() 唤醒此对象监视器上等待的单个线程,使这个线程进入就绪状态
* Object.notifyAll() 唤醒所有处于等待状态的线程,使其进入就绪状态
* Thread.getState() 获取线程当前的状态
*/
/**
* 说下线程的状态:
* 1. NEW 新建
* 2. RUNNABLE 运行
* 3. BLOCKED 就绪
* 4. WAITING 等待
* 5. TIME_WAITING 等待(一定时间后就会自动被唤醒)
* 6. TERMINATED 停止
*
* 可以看到和我们上节课所教的状态是一一对应的(TIME_WAITING也是等待,只不过是一种特殊的等待)
*/
//来试试
MyThread1 myThread1 = new MyThread1("线程1");
MyThread1 myThread2 = new MyThread1("线程2");
//在启动前让他们可以获取对方的状态
myThread1.setOtherThread(myThread2);
myThread2.setOtherThread(myThread1);
//来看看启动前的状态
System.out.println(myThread1.getName() + "的状态是" + myThread1.getState());
System.out.println(myThread2.getName() + "的状态是" + myThread2.getState());
myThread1.start();
myThread2.start();
//等待状态下节课讲吧。。我再去看看。。
}
}
class MyThread1 extends Thread{
//本属性决定当前线程是否停止运行,当其为false时,停止运行
//这种停止线程运行的方法时jdk推荐的,因为stop()方法过时了
private boolean flag = true;
private Thread otherThread = null;
int i;
public MyThread1() {
super();
}
public MyThread1(Runnable target) {
super(target);
}
public MyThread1(String name) {
super(name);
}
/**
* @return 返回该线程的Id,线程Id是自动生成的,且唯一
*/
@Override
public long getId() {
return super.getId();
}
//改下run方法
@Override
public void run() {
while(flag)
{
System.out.println("我是" + getName() + ",我的状态为" + getState());
System.out.println("另一个线程是" + otherThread.getName() + ",他的状态为" + otherThread.getState());
i++;
if (i == 10)
{
stopThread();//给个结束条件
}
//让出资源
// yield();
}
}
public void stopThread()
{
flag = false;
}
public Thread getOtherThread() {
return otherThread;
}
public void setOtherThread(Thread otherThread) {
this.otherThread = otherThread;
}
}