Java多线程技能--01

说明:参考《Java多线程核心技术》

1、区分进程和线程

进程:进程是操作系统结构的基础,是一次程序的进行,简单理解为OS中运行的exe程序。
线程:进程中独立运行的子任务。可能一个进程中有许多的子任务,这些任务可以同时运行。比如:你在微信视频聊天的同时,可以给另一个人发微信表情。

2、继承Thread类
public class ThreadTest01 {
    public static void main(String[] args) {
        Thread01 thread01 = new Thread01();
        thread01.start();
        System.out.println("结束了");
    }
}
public class Thread01 extends Thread{
    @Override
    public void run() {
        super.run();
        System.out.println("first Thread");
    }
}
/**
 * 结束了
 * first Thread
 */

在使用多线程时,运行结果与代码的执行顺序或者调用顺序是无关的。

public class Thread02 extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("----" + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class ThreadTest02 {
    public static void main(String[] args) {
        try {
            Thread02 thread02 = new Thread02();
            thread02.setName("testThread");
            thread02.start();
            for (int i = 0; i < 100 ; i++) {
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("mainThread" + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/**
  mainThreadmain
 ----testThread
 mainThreadmain
 ----testThread
 mainThreadmain
 mainThreadmain
 * */

Thread.java中的start()方法通知线程管理器当前线程已经准备好了,等待调用线程对象的run()方法,具有异步执行的效果。

3、实现Runnable接口

如果创建的类已经有父类了,那么可以利用实现Runnable接口来实现。

public class Runnable01 implements Runnable{
    @Override
    public void run() {
        System.out.println("--运行中...");
    }
}
public class RunnableTest01 {
    public static void main(String[] args) {
        Runnable runnable = new Runnable01();
        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println("--运行结束");
    }
}
/***
 --运行结束
 --运行中...
 */

注意: Thread.java同样也实现了Runnable接口。

public class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值