3

java | 多线程基础

 1 year ago
source link: https://benpaodewoniu.github.io/2022/11/19/java54/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

简单的介绍 java 的多线程。

Thread

public class T extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {

System.out.println(1);
}
}

public static void main(String[] args) {
T t = new T();
t.start();

for (int i = 0; i < 1000; i++) {
System.out.println(2);
}
}
}

new 一个 Thread 类或者子类对象时,非静态属性(实例属性)都会在内存中重新加载,起不到共用资源的效果,因此我们需要将共用的对象或者变量用static修饰,使其成为类属性,在内存中只加载一次。

Runnable 接口

public class T implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {

System.out.println(1);
}
}

public static void main(String[] args) {
T t = new T();
new Thread(new T()).start();

for (int i = 0; i < 1000; i++) {
System.out.println(2);
}
}
}

通过实现Runnable接口,通过同一个Runnable接口实现类对象创建多个线程,则多个线程共享Runnable对象。

类似下面的代码

package com.example.blog;

import lombok.SneakyThrows;

public class T implements Runnable {

public int number = 10;

@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (number < 0) {
return;
}
try {
Thread.sleep(200);
} catch (Exception e) {
;
}
System.out.println(Thread.currentThread() + String.valueOf(number--));
}
}

public static void main(String[] args) {
T t = new T();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
// 下面这个不行
// new Thread(new T()).start();
// new Thread(new T()).start();
// new Thread(new T()).start();
}
}

但是,上面的代码运行的时候,会出现资源重复利用的现象。所以要加锁。

callable

package com.example.blog;

import lombok.SneakyThrows;

import java.util.concurrent.*;

public class T implements Callable<Boolean> {

public int number = 10;

@Override
public Boolean call() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread() + String.valueOf(number--));
}
return true;
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
T t1 = new T();
T t2 = new T();
T t3 = new T();

// 线程池
ExecutorService ser = Executors.newFixedThreadPool(3);

// 提交任务
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);

// 获取结果

Boolean b1 = r1.get();
Boolean b2 = r2.get();
Boolean b3 = r3.get();

// 关闭池子
ser.shutdown();
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK