Java笔记15:多线程

来源:互联网 发布:数据库isnull 编辑:程序博客网 时间:2024/05/24 06:51

Java实现多线程有两种方式:一是继承Thread类;二是实现Runable接口。

一、Thread实现

publicclass ThreadDemo2 {    publicstaticvoid main(String[] args) {        new TestThread2().start();        inti = 0;        while(i++ < 100) {            System.out.println("main thread is running");        }    }} class TestThread2 extends Thread {    publicvoid run() {        intj = 0;        while(j++ < 100) {            System.out.println(Thread.currentThread().getName() + " is running!");        }    }}

运行结果:

 

二、Runnable实现

publicclass ThreadDemo3 {    publicstaticvoid main(String[] args) {        TestThread3 t3 = new TestThread3();        Thread t = new Thread(t3);        t.start();        inti = 0;        while(i++ < 100) {            System.out.println("main thread is running");        }            }} class TestThread3 implements Runnable {    publicvoid run() {        intj = 0;        while(j++ < 100) {            System.out.println(Thread.currentThread().getName() + " is running!");        }    }}

运行结果:

 

0 0
原创粉丝点击