Thread类中常用的方法
构造方法:无参的构造方法 Thread()
Thread(Runnable target) 传入一个实现了Runnable接口的对象
Thread(Runnable target, String name) name为给线程取的名字
Thread(String name) name为给线程取的名字
普通方法:long getId() 返回线程的id String String getName() 返回线程的名字 int getPriority()返回线程的优先级
currentThread(),返回当前正在执行的现程对象 setName(String name) 设置线程名字 setPriority(int priority) 设置优先级
sleep(long millis) 是当前线程睡眠指定的毫秒数,是线程进入阻塞状态,可以被打断,需要捕获InterruptedException
````java
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
·```
start(),是线程开始执行,Java虚拟机调用线程的run方法
yield(),暂停当前执行的线程,进入就绪状态,让出CPU资源,让其他线程使用
join(),使其他线程等待该线程终止,比如一个线程A调用线程B的join()方法,那么线程A只有当线程B执行完以后才开始执行
int count = 0;
synchronized void m(){
for(int i = 0 ; i < 20; i++){
count++;
}
}
public static void main(String[] args) {
final Test04 t = new Test04();
Thread[] threads = new Thread[10];
//放入十个线程
for(int i = 0; i < threads.length; i++){
threads[i] = new Thread(new Runnable(){
@Override
public void run() {
t.m();
}
});
}
for(Thread thread : threads){
thread.start();
}
for(Thread thread : threads){
try {
thread.join();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
System.out.println(t.count); //结果是200,如果不使用join()方法,count可能是0-200中的任意值
}