java 多线程

线程的三种状态: 新建, 运行, 就绪,阻塞,死亡
线程运行流程图
thread

java中要使用线程有两种方法:

1. 继承Thread 类 并重写run函数 。通过start()函数启动

2. 实现Runable接口,并重写run函数。 通过创建new 一个Thread 然再start来启动

两个简单的java 线程例子 分别通过继承Thread 类 和 实现Runnable 接口的run 函数来实现线程:

package Threading;

/** java 多线程
 * java中要使用线程有两种方法:
 *   1. 继承Thread 类 并重写run函数
 *   2. 实现Runable接口,并重写run函数
 * Created by admin on 2017/7/30.
 */
public class JavaThread {
    public static void main(String[] args){
        Cat cat = new Cat();
        // 通过start 方法运行线程, 会直接运行run 函数
        cat.start();
        Cat2 cat2 = new Cat2();
        Thread thread = new Thread(cat2);
        thread.start();
    }
}
// 第一种方法,通过继承Thread 重写run 函数实现线程
class Cat extends Thread{
    int times=0;
    public void run(){
        while (true){
            // 让线程休眠 一秒. sleep 的参数是毫秒 1000 毫秒 等于 1 秒
            // sleep 会导致线程进入阻塞(Blocked)状态
            // 必须要使用try catch
            try{
                Thread.sleep(1000);
            }catch (InterruptedException ie){
                ie.printStackTrace();
            }
            times++;
            System.out.println("Hello World"+times);
            if (times == 10){
                break;
            }
        }
    }
}
// 通过实现Runnable接口来使用线程
class Cat2 implements Runnable{
    @Override
    public void run() {
       for (int i=0; i<=10; i++){
           try{
               Thread.sleep(1000);
           }catch (InterruptedException ie){
               ie.printStackTrace();
           }
           System.out.println("Cat2 out"+i);
       }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值