Thread类包含的方法
start() 启动线程
isAlive() 判断线程当前是否正在运行
setPriority() 设置优先级
jion() 使一个线程等待另一个线程结束
sleep(mills:long) 指定线程休眠指定毫秒
sleep()方法可能抛出一个InterruptedException,这是一个必检异常,因此sleep()
方法必须放在try-catch语句块内
jion() 使一个线程等待另一个线程结束
setPriority(),在主程序中调用,用以设置优先级,Thread类下定义了三个int型的优先级
MIN_PRIORITY=1,MAX_PRIORITY=10,NORM_PRIORITY=5
wait() 和notify()与Synchronized关键字在下一节一起学习
start() 启动线程
isAlive() 判断线程当前是否正在运行
setPriority() 设置优先级
jion() 使一个线程等待另一个线程结束
sleep(mills:long) 指定线程休眠指定毫秒
yield() 使线程暂停并允许执行其他进程
wait() 和notify() 等待与唤醒
interrupt() 中断线程(极少使用)
yield():
public class PrintChar implements Runnable {
char ch;
int count=0;
public PrintChar(char ch,int count){
this.ch=ch;
this.count=count;
}
public void run() {
for(int i=0;i<count;i++){
System.out.print(" "+ch);
Thread.yield();
}
}
}
sleep()方法可能抛出一个InterruptedException,这是一个必检异常,因此sleep()
方法必须放在try-catch语句块内
public class PrintNum implements Runnable{
int num;
int count;
public PrintNum (int Num,int count){
this.num=Num;
this.count=count;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<count;i++){
System.out.print(num);
if(i>20){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
jion() 使一个线程等待另一个线程结束
public class PrintChar implements Runnable {
char ch;
int count=0;
Thread print_num =new Thread(new PrintNum('b', 20));
public PrintChar(char ch,int count){
this.ch=ch;
this.count=count;
}
public void run() {
for(int i=0;i<count;i++){
System.out.print(" "+ch);
if (i==30) {
try {
print_num.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
setPriority(),在主程序中调用,用以设置优先级,Thread类下定义了三个int型的优先级
MIN_PRIORITY=1,MAX_PRIORITY=10,NORM_PRIORITY=5
public class Print {
public static void main(String[] args) {
Runnable pc=new PrintChar('A', 100);
Runnable pn=new PrintNum(9, 100);
Thread th1=new Thread(pc);
Thread th2=new Thread(pn);
th1.setPriority(Thread.MIN_PRIORITY);
th1.start();
th2.start();
}
}
wait() 和notify()与Synchronized关键字在下一节一起学习