继承Thread(不推荐使用,具有单继承局限性)
| public class StartThread extends Thread{ |
| |
| |
| |
| @Override |
| public void run() { |
| for (int i = 0; i < 1000; i++) { |
| System.out.println(i+"杨玉环真好玩!"); |
| } |
| } |
| |
| public static void main(String[] args) { |
| |
| |
| StartThread startThread = new StartThread(); |
| startThread.start(); |
| |
| |
| |
| for (int i = 0; i < 10000; i++) { |
| System.out.println("鲁班好可爱"); |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| } |
| } |
实现Runnable(推荐使用,它可以对同一资源开启多个线程)
| package com.Luoking.Thread; |
| |
| public class Runnable01 implements Runnable{ |
| private int ticket = 100; |
| |
| @Override |
| public void run() { |
| while(true){ |
| if(ticket<=0){ |
| break; |
| } |
| System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket+"张票"); |
| ticket--; |
| } |
| } |
| |
| |
| public static void main(String[] args) { |
| Runnable01 runnable01 = new Runnable01(); |
| new Thread(runnable01,"小敏").start(); |
| new Thread(runnable01,"小杰").start(); |
| new Thread(runnable01,"小平").start(); |
| } |
| } |
但是实现Runable会出现并发问题,多个线程操作同一个资源,会出现线程不安全,数据紊乱
| 小敏拿到了第100张票 |
| 小敏拿到了第99张票 |
| 小敏拿到了第98张票 |
| 小杰拿到了第100张票 |
| |
| |
实现callable
| package com.Luoking.Thread; |
| |
| import java.util.concurrent.*; |
| |
| public class testCallable implements Callable<Boolean> { |
| |
| @Override |
| public Boolean call() throws Exception { |
| for (int i = 0; i < 10; i++) { |
| System.out.println("执行到"+i+"步"); |
| } |
| return true; |
| } |
| |
| public static void main(String[] args) throws ExecutionException, InterruptedException { |
| testCallable T1 = new testCallable(); |
| testCallable T2 = new testCallable(); |
| testCallable T3 = new testCallable(); |
| |
| ExecutorService pool = Executors.newFixedThreadPool(3); |
| |
| Future<Boolean> s1 = pool.submit(T1); |
| Future<Boolean> s2 = pool.submit(T2); |
| Future<Boolean> s3 = pool.submit(T3); |
| |
| |
| Boolean b1 = s1.get(); |
| Boolean b2 = s1.get(); |
| Boolean b3 = s1.get(); |
| |
| |
| pool.shutdownNow(); |
| |
| } |
| |
| } |
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决