java线程的学习

目录

一、继承Thread类实现多线程 

线程不一定执行,cpu安排调度  

二、实现Runnable接口实现多线程

currentThread()方法返回正在被执行的线程的信息。

三、Callable接口实现多线程 

1|0一、继承Thread类实现多线程 

1|1线程不一定执行,cpu安排调度  

在线程中主线程和分线程是一起执行的    -------调用start

调用run方法时则是有先后顺序的  

package ThreadDemo1; public class Threadstudy extends Thread{ public void run(){ for (int i = 0; i < 20; i++) { System.out.println("分线程"+i); } } public static void main(String[] args) { Threadstudy threadstudy = new Threadstudy(); threadstudy.start(); for (int i = 0; i < 200; i++) { System.out.println("主线程"+i); } } }

2|0二、实现Runnable接口实现多线程

 Thread在源码中的定义 

public class Thread implements Runnable { /* Make sure registerNatives is the first thing <clinit> does. */ private static native void registerNatives(); static { registerNatives(); }

 所以Thread已经实现了Runnable接口(和上面只继承Thread的方法一样):

可以避免单继承的局限性、灵活方便、方便同一个对象被多个线程使用也就是Runnable一个对象,将这个对象 可以放在不同的Thread对象里面使用;

package ThreadDemo1; public class Runnablestudy implements Runnable{ public void run(){ for (int i = 0; i < 20; i++) { System.out.println("分线程的学习"+i); } } public static void main(String[] args) { Runnablestudy runnablestudy = new Runnablestudy(); Thread thread = new Thread(runnablestudy); thread.start(); for (int i = 0; i < 200; i++) { System.out.println("多线程的学习"+i); } } }

 利用龟兔赛跑实现多线程的进行Runnable接口

2|1currentThread()方法返回正在被执行的线程的信息。

package ThreadDemo1; //龟兔赛跑实现线程 public class Runnablestudy implements Runnable{ private static String winner; public void run(){ for (int i = 0; i <=100; i++) { //模拟兔子休息 if(Thread.currentThread().getName().equals("兔子")&&i%10==0){ try{ //程序暂停1ms Thread.sleep(1); }catch(InterruptedException e){ //输出错误信息 e.printStackTrace(); } } boolean flag = gameOver(i); if(flag){ break; } //输出谁走了多少步 System.out.println(Thread.currentThread().getName()+"跑了"+i+"步"); } } //判断是否完成比赛 public boolean gameOver(int steps){ if(winner!=null){ return true; } { if (steps >= 100) { winner = Thread.currentThread().getName(); System.out.println("winner is" + winner); return true; } } return false; } public static void main(String[] args) { Runnablestudy race = new Runnablestudy(); new Thread(race,"兔子").start(); new Thread(race,"乌龟").start(); } }

3|0三、Callable接口实现多线程 

 

 

 


__EOF__

本文作者userName
本文链接https://www.cnblogs.com/20kkk/p/16537555.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   鹅城小铁匠  阅读(18)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
Fork me on GitHub
点击右上角即可分享
微信分享提示