线程操作的相关方法
Thread类中的主要方法
表:
序号 | 方法名称 | 类型 | 描述 |
---|---|---|---|
1 | public Thread(Runnable target) | 构造 | 接收Runnable接口子类对象,实例化Thread对象 |
2 | public Thread(Runnable target,String name) | 构造 | 接收Runnable接口子类对象,实例化Thread对象,并设置线程名称 |
3 | public Thread(String name) | 构造 | 实例化Thread对象,并设置线程名称 |
4 | public static Thread currentThread() | 普通 | 返回目前正在执行的线程 |
5 | public final String getName() | 普通 | 返回线程的名称 |
6 | public final int getPriority() | 普通 | 返回线程的优先级 |
7 | public boolean isInterrupted() | 普通 | 判断目前线程是否被中断 |
8 | public final boolean isAlive() | 普通 | 判断线程是否在活动 |
9 | public final void join() throws InterruptedException | 普通 | 使线程强制运行,其他线程必须等待此线程完成才可以继续执行 |
10 | public final synchronized void join(long millis) throws InterruptedException | 普通 | 使线程强制运行,等待millis毫秒,其他线程必须等待此线程完成才可以继续执行 |
11 | public void run() | 普通 | 执行线程 |
12 | public final void setName(String name) | 普通 | 设定线程名称 |
13 | public final void setPriority(int newPriority) | 普通 | 设置线程的优先级 |
14 | public static void sleep(long millis) throws InterruptedException | 普通 | 使目前正在执行的线程休眠millis毫秒 |
15 | public void start() | 普通 | 开始执行线程 |
16 | public String toString() | 普通 | 返回代表线程的字符串 |
17 | public static void yield() | 普通 | 将目前执行的线程暂停,允许其他线程执行 |
18 | public final void setDaemon(boolean on) | 普通 | 将一个线程设置成后台运行 |
currentThread()方法与getName()方法使用实例
例1、
class MyThread implements Runnable{
public void run(){
for(int i=0;i<3;i++){
System.out.println(Thread.currentThread().getName()+"运行,i="+i);
}
}
}
public class Demo{
public static void main(String[] args){
MyThread my=new MyThread();
new Thread(my).start();
new Thread(my,"线程-A").start();
new Thread(my,"线程-B").start();
new Thread(my).start();
new Thread(my).start();
}
}
Thread-0运行,i=0
Thread-1运行,i=0
Thread-1运行,i=1
线程-B运行,i=0
线程-B运行,i=1
线程-B运行,i=2
线程-A运行,i=0
线程-A运行,i=1
Thread-1运行,i=2
Thread-2运行,i=0
Thread-0运行,i=1
Thread-0运行,i=2
Thread-2运行,i=1
Thread-2运行,i=2
线程-A运行,i=2
例2、
class MyThread implements Runnable{
public void run(){
for(int i=0;i<3;i++){
System.out.println(Thread.currentThread().getName()+"运行,i="+i);
}
}
}
public class Demo1{
public static void main(String[] args){
MyThread my=new MyThread();
new Thread(my,"线程").start();
my.run();
}
}
main运行,i=0
线程运行,i=0
main运行,i=1
main运行,i=2
线程运行,i=1
线程运行,i=2
可以看出主方法实际上也是一个线程。
Thread.sleep()方法使用实例
class MyThread implements Runnable{
public void run(){
for(int i=0;i<5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"运行,i="+i);
}
}
}
public class Demo1{
public static void main(String[] args){
MyThread my=new MyThread();
new Thread(my,"线程").start();
}
}
线程优先级
在Java的线程中使用setPriority()方法设置一个线程的优先级
序号 | 定义 | 描述 | 表示的常量 |
---|---|---|---|
1 | public static final int MiN_PRIORITY | 最低优先级 | 1 |
2 | public static final int NORM_PRIORITY | 中等优先级,是线程默认的优先级 | 5 |
3 | public static final int MAX_PRIORITY | 最高优先级 | 10 |
线程根据其被设置的优先级的大小来决定哪个线程会先运行。但注意的是,并不一定线程的优先级高就一定会执行,哪个线程先执行将有CPU的调度决定。