码迷,mamicode.com
首页 > 编程语言 > 详细

java基础---->java多线程的使用(一)

时间:2017-07-25 22:41:43      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:简单   ble   多线程   interrupt   run   catch   static   try   实现   

  java线程的创建有两种方式,这里我们通过简单的实例来学习一下。

 

java中多线程的创建

一、通过继承Thread类来创建多线程

public class HelloThread extends Thread {
    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("Hello from a thread!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        HelloThread helloThread = new HelloThread();
        helloThread.start();
        System.out.println("In main thread.");
    }
}

运行的结果如下:

In main thread.
Hello from a thread!

 

二、通过实现Runnable接口来创建多线程

public class HelloRunnable implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println("Hello from a thread!");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new HelloRunnable());
        thread.start();
        System.out.println("In main method.");
    }
}

运行的结果如下:

In main method.
Hello from a thread!

 

友情链接

 

java基础---->java多线程的使用(一)

标签:简单   ble   多线程   interrupt   run   catch   static   try   实现   

原文地址:http://www.cnblogs.com/huhx/p/baseusejavathread1.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!