Java多线程的学习和应用

Java实现多线程有两种方式:

1.继承Thread类,重写run方法

package com.bjdata.test;

public class ThreadTest extends Thread{
    String name="";
    public ThreadTest(String n){
        name=n;
    }
    public void run(){
        for(int i=0;i<6;i++){
            System.out.println(name+":hello:"+i);
        }
    }
    public static void main(String[] args) {
        ThreadTest test1=new ThreadTest("A");
        ThreadTest test2=new ThreadTest("B");
        test1.start();
        test2.start();
    }

}

注意:程序运行的时候调用的是start方法,而不是run方法

第一次运行结果:

A:hello:0
B:hello:0
B:hello:1
B:hello:2
B:hello:3
B:hello:4
B:hello:5
A:hello:1
A:hello:2
A:hello:3
A:hello:4
A:hello:5

第二次运行结果:

B:hello:0
B:hello:1
B:hello:2
B:hello:3
B:hello:4
B:hello:5
A:hello:0
A:hello:1
A:hello:2
A:hello:3
A:hello:4
A:hello:5

两次运行结果不一致,说明我们的目的达到了

2.实现Runnable

package com.bjdata.test;

public class RunableTest implements Runnable{
    String name="";
    public RunableTest(String n){
        name=n;
    }
    public void run(){
        for(int i=0;i<6;i++){
            System.out.println(name+":hello:"+i);
        }
    }
    public static void main(String[] args) {
        RunableTest test1=new RunableTest("A");
        RunableTest test2=new RunableTest("B");
        Thread thread1=new Thread(test1);
        Thread thread2=new Thread(test2);
        thread1.start();
        thread2.start();
    }

}

第一次运行结果

A:hello:0
A:hello:1
A:hello:2
A:hello:3
A:hello:4
A:hello:5
B:hello:0
B:hello:1
B:hello:2
B:hello:3
B:hello:4
B:hello:5

第二次运行

A:hello:0
A:hello:1
A:hello:2
B:hello:0
B:hello:1
B:hello:2
B:hello:3
B:hello:4
B:hello:5
A:hello:3
A:hello:4
A:hello:5

注意:运行时,要先创建Thread对象,把需要多线程运行的事例传进去,然后调用Thread的run方法

原文地址:https://www.cnblogs.com/zhanghaoh/p/2817159.html