多线程是Java学习中的一个很重要的知识点,对于多线程的五种状态运行机制等,开头不再多讲,因为,怕大家看了开始就头大,后面的内容就不想了解了。我们先从简单实用的开始:
第一种方法继承Thread创建多线程:
Java中万物皆对象,多线程也不例外,脑海中第一个想法就是要创建一个类继承Thread父类。并且重写父类中的run方法。
直接上代码:
class MyThread extends Thread {
private int i = 0;
public void run() {
for (i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " " + i); }
}
}
public class ThreadTest {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 30) {
Thread myThread1 = new MyThread();
// 创建一个新的线程 myThread1 此线程进入新建状态
Thread myThread2 = new MyThread();
// 创建一个新的线程 myThread2 此线程进入新建状态
myThread1.start();
// 调用start()方法使得线程进入就绪状态
myThread2.start();
// 调用start()方法使得线程进入就绪状态
}
}
}
}
第二种方法:实现Runnable接口,并重写该接口的run()方法:
class MyRunnable implements Runnable {
private int i = 0;
public void run() {
for (i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
} //实现Runnable接口
public class ThreadTest {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 30) {
Runnable myRunnable = new MyRunnable();
// 创建一个Runnable实现类的对象
Thread thread1 = new Thread(myRunnable);
// 将myRunnable作为Thread target创建新的线程
Thread thread2 = new Thread(myRunnable);
thread1.start();
// 调用start()方法使得线程进入就绪状态
thread2.start();
}
}
}
}