//MyThread.javapublicclassMyThreadextendsThread{// MyThread就是一个线程类。@Overridepublicvoidrun(){for(int i =0; i <1000; i++){System.out.println("MyThread在执行--->"+ i);}}}//ThreadTest01.javapublicclassThreadTest01{// 通过继承Thread类来创建线程publicstaticvoidmain(String[] args){// 怎么创建线程对象?MyThread t =newMyThread();// t就是一个线程对象。// 怎么启动一个线程?// 以下代码表示在主线程中,使用线程的start方法来启动分支线程。// 分支线程的启动,表示在JVM当中分配一个新的栈内存。
t.start();// 这个方法调用之后,会开启新的栈内存。开启一个新的分支线程。(只要开启之后两个线程就互不干扰了。各自执行各自的。)//t.run(); // 这不会启动新的线程,只是普通方法调用。for(int i =0; i <1000; i++){System.out.println("main线程--->"+ i);}}}
实现Runnable接口,实现run方法
//MyRunnable.javapublicclassMyRunnableimplementsRunnable{// MyRunnable不是一个线程,只是一个实现了Runnable接口的类。@Overridepublicvoidrun(){for(int i =0; i <1000; i++){System.out.println("MyRunnable--->"+ i);}}}//ThreadTest01.javapublicclassThreadTest01{publicstaticvoidmain(String[] args){// 创建线程对象Thread t =newThread(newMyRunnable());// 启动线程
t.start();for(int i =0; i <1000; i++){System.out.println("main线程---->"+ i);}newThread(()->{System.out.println("x线程执行了。");}).start();}}
三.获取当前线程对象的引用
publicclassThreadTest01{//获得当前线程对象的引用publicstaticvoidmain(String[] args){Thread t =newMyThread();
t.setName("t线程");
t.start();// 这个代码出现在主线程中,那么获取的当前线程对象一定是主线程。Thread x =Thread.currentThread();System.out.println(x.getName());}}classMyThreadextendsThread{@Overridepublicvoidrun(){for(int i =0; i <10; i++){// 这里怎么获取当前线程对象?//System.out.println(Thread.currentThread());Thread t =Thread.currentThread();//System.out.println(t == this);// 获取当前线程的名字System.out.println("当前线程名:"+ t.getName());}}}
四.线程的生命周期
五.线程的休眠
publicclassThreadTest{// 线程睡眠,会放弃占有的CPUpublicstaticvoidmain(String[] args){Thread t =newMyThread();
t.setName("t");
t.start();// Thread.sleep(毫秒)// 静态方法// 单位是毫秒// 出现在哪里就阻塞哪里。表示让当前线程进入休眠状态。// 如果写到这里就是让主线程进入休眠for(int i =0; i <10; i++){System.out.println(Thread.currentThread().getName()+"==>"+ i);try{Thread.sleep(300);}catch(InterruptedException e){
e.printStackTrace();}}}}classMyThreadextendsThread{publicvoidrun(){for(int i =0; i <10; i++){System.out.println(Thread.currentThread().getName()+"==>"+ i);try{Thread.sleep(400);}catch(InterruptedException e){
e.printStackTrace();}}}}
六.后台线程的特点
publicclassThreadTest01{/*
守护线程/后台线程:
1.线程分类:
第一类:用户线程/前台线程
第二类:守护线程/后台线程。
2.所有的守护线程一般情况下是不会结束的,守护线程在什么时候会结束呢?
当所有的用户线程结束之后,守护线程自动结束。
3. java程序中有一个非常经典的守护线程:垃圾回收线程。
*/publicstaticvoidmain(String[] args){// t线程是守护线程// main线程是用户线程Thread t =newMyThread();
t.setName("t");// 将t线程设置为后台线程。
t.setDaemon(true);
t.start();for(int i =0; i <10; i++){try{Thread.sleep(500);}catch(InterruptedException e){
e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"--->"+ i);}}}classMyThreadextendsThread{publicvoidrun(){int i =0;while(true){
i++;try{Thread.sleep(1000);}catch(InterruptedException e){
e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"==>"+ i);}}}