有两种方法可以书写多线程
第一种是继承线程类,重写Run方法,如代码所示
一定要在主线程创建对象,然后去实现start方法,这样才能多线程输出
public class ThreadTest02 { public static void main(String[] args) { Thread mt = new myThread2(); Thread.currentThread().setName("main"); mt.setName("t1"); mt.start(); for (int i = 0; i < 1000; i++) { System.out.println(Thread.currentThread().getName() + "---->" + i); } } } class myThread2 extends Thread { @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println( Thread.currentThread().getName() + "---->" + i); } } }
输出的片段如下:(只要是输出的有两个线程即可,不需要是交替输出)
t1---->0
main---->0
t1---->1
main---->1
t1---->2
main---->2
t1---->3
main---->3
t1---->4
另一种输出的格式是实现Runnable接口,重写run方法
public class ThreadTest01 { public static void main(String[] args) { myThread m = new myThread(); Thread t = new Thread(m); // Thread-0这是默认状态下线程的名字,可以进行修改和输出 t.setName("香风智乃"); t.start(); System.out.println(t.getName()); for(int i = 0; i <1000; i++){ System.out.println(Thread.currentThread().getName() + "----->" + i); } } }
class myThread implements Runnable{ @Override public void run() { for(int i =0; i<1000;i++){ System.out.println(Thread.currentThread().getName() + "----->" + i); } } }
输出的片段和第一个差不多
需要注意,如果是循环的话,那么多线程的每次输出的数据都大概率是不同的。。。
以上就是创建多线程的两种方法。。。