一、实现多线程的编程方式
1. 继承 Thread 类
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("实现多线程方式:继承Thread类");
}
}
2. 实现 Runnable 接口
public class MyRunnable implements Runnable {
public void run() {
System.out.println("实现多线程方式:实现Runnable接口");
}
}
二、多线程的运行随机性
在多线程编程中,代码的运行顺序是随机的。
代码的运行结果与代码的执行顺序或调用顺序是无关的。
线程是一个子任务,CPU以不确定的方式,或者说是以随机的时间来调用线程中的run方法。
@Test
public void testMyRandomThread() {
MyRandomThread myRandomThread = new MyRandomThread();
myRandomThread.setName("MyRandomThread");
myRandomThread.start();
for (int i=0; i<5; i++) {
int time = (int) (Math.random() * 1000);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run=" + Thread.currentThread().getName());
}
}
public class MyRandomThread extends MyThread {
@Override
public void run() {
for (int i=0; i<5; i++) {
int time = (int) (Math.random() * 1000);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run=" + Thread.currentThread().getName());
}
}
}
执行结果:
run=main
run=MyRandomThread
run=main
run=MyRandomThread
run=MyRandomThread
run=main
run=main
run=MyRandomThread
run=main
三、currentThread() 方法
Thread 类的 currentThread() 方法可返回代码段正在被哪个线程调用的信息。
@Test
public void testMyCurrentThread() throws Exception {
MyCurrentThread myCurrentThread = new MyCurrentThread();
myCurrentThread.start();
myCurrentThread.join();
System.out.println("-----------------------");
MyCurrentThread myCurrentThread1 = new MyCurrentThread();
myCurrentThread1.run();
}
public class MyCurrentThread extends Thread {
public MyCurrentThread() {
System.out.println("构造方法的打印:【currentThread】" + " " + Thread.currentThread().getName());
}
@Override
public void run() {
System.out.println("执行run方法:【currentThread】" + " " + Thread.currentThread().getName());
}
}
执行结果:
构造方法的打印:【currentThread】 main
执行run方法:【currentThread】 Thread-0
-----------------------
构造方法的打印:【currentThread】 main
执行run方法:【currentThread】 main