案例1:
public class Diom01 {
public static void main(String[] args) {
Thread minth = new Thread(new th(), "优先级较低的线程");1
Thread maxth = new Thread(new th(), "优先级较高的线程");
maxth.setPriority(Thread.MAX_PRIORITY);2
minth.setPriority(Thread.MIN_PRIORITY);
minth.start();
maxth.start();
}
}
class th implements Runnable {
@Override
public void run() {3
for (int i = 0; i <= 10; i++) {
//Thread.currentThread()调用thread方法获取当前线程对象
System.out.println(Thread.currentThread().getName() + "正在输出" + i);
}
}
}
1、多线程有两种创建方法
1)Thread 命名=new Thread(new 定义的成员方法或线程名(),“定义线程name”);
2)new Thread(new 线程名()).start();
2、定义线程优先级
创建的线程命名.setPriority(Thread.MIN_PRIORITY或者Thread.MAX_PRIORITY);
3、进程休眠
Thread.sleep(2000);
修改数字即可(1s=1000ms)
4、一切进程都要写在run()方法里
5、sleep方法直接运行会出现错误,因此要放在try()catch{}方法中抛出异常