线程

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