- 测试Thread中的常用方法
- 1.stat();启动当前线程,并调用当前线程的run()
- 2.run();
- 3.currentcThread();静态方法,返回执行当前代码的线程
- 4.getName();
- 5.setName();
- 6.yield();释放当cpu的执行权,有可能还是当前的获取
- 7.join();分线程加入,执行完后,主线程才执行。当主线程需要分线程执行完的数据时使用。
- a中调用b的join,此时a进入阻塞状态,知道b执行完。
- 8.stop();deprecated 不建议使用,过时。
- 9.sleep();阻塞时间为ms
-
- isAlive;判断线程是否存活
-
- 线程的优先级:
-
- MAX_PRIORITY:10 最高
- MIN_PRIORITY:1 最低
- NORM_PRIORITY:5 普通
- 高优先级要抢占低优先级的线程,只是概率上的高,不是绝对的高优先级全部执行完后,低优先级才执行
-
- getPriority() 获取优先级
- setPriority() 设置优先级
下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
// An highlighted block
class MThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + i + getPriority() + "副线程");
}
if (i % 20 == 0) {
yield();
}
}
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
MThread t1 = new MThread();
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();//启动当前线程,调用当前线程的run方法
// t1.run(); //只调用方法,不是多线程
System.out.println("thread test");
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + i + Thread.currentThread().getPriority() + "**********主线程**********");
}
if (i == 20) {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(t1.isAlive());
}
}