线程

01:线程入门

 

 

 

创建线程的目的是为了开启一条执行路径,去运行指定的代码和其他代码实现同时运行。

 

而运行的指定代码就是这个执行路径的任务。



jvm创建的主线程的任务都定义在了主函数中。

 

而自定的线程它的任务在哪儿呢?

 

这个任务通过Thread类中的run方法来体现。也就是说,run方法就是封装自定义线程运行任务的函数。

 

run方法中定义的就是线程要运行的任务代码。

 

开启线程是为了运行指定代码,所以只有继承Thread类,并复写run方法。

 

将运行的代码定义在run方法中即可。

02:实现方式。01—继承Thread,重写run方法,start启动。

class Demo extends Thread{
private String name;
Demo(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(name+""+i);
}
}
}
public class ThreadDemo extends Thread{
public static void main(String[] args) {
Demo d1=new Demo("旺财");
Demo d2=new Demo("XIAOQIANG");
d1.start();//开启线程
d2.start();
}
}

 02:实现Runnable接口,开启线程。

 1 package com.google.thread;
 2 class Ticker implements Runnable{
 3     public int num = 100;
 4 
 5     public void run() {
 6         while (true) {
 7             if (num > 0) {
 8                 System.out.println(Thread.currentThread().getName() + "...." + num--);
 9             }
10         }
11     }
12 }
13 
14 public class ThreadDemo extends Thread {
15     public static void main(String[] args) {
16         Ticker t = new Ticker();
17         Thread t1=new Thread(t);
18         Thread t2=new Thread(t);
19         Thread t3=new Thread(t);
20         Thread t4=new Thread(t);
21         t1.start();
22         t2.start();
23         t3.start();
24         t4.start();
25     }
26 }

 

转载于:https://www.cnblogs.com/CAOXIAOYANG/p/8871705.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值