Thread 接口和 Runnable 接口,资源共享

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.demo;

public class ThreadTest {
// 主方法
public static void main(String args[]) {
MyThread a = new MyThread();
a.setMyThreadName("xiaoming");

a.setPriority(1); // 设置优先级,值为1-10,主方法的优先级为5
a.setPriority(Thread.MIN_PRIORITY);
a.setPriority(Thread.MAX_PRIORITY);

a.start(); //线程必须通过start方法启动,start会调用不同系统的api线程接口,再执行run方法

MyThread2 b = new MyThread2();
b.setMyThreadName("xiaohong");
new Thread(b).start(); // 通过new Thread创建多线程
new Thread(b).start(); // 资源共享

new Thread(() -> { // 直接使用函数式
for (int i = 0; i < 100; i++) {
System.out.println( i + ".xiaofang");
}
}).start();
}
}

class MyThread extends Thread{
private String name;

@Override
public void run() { // 必须复写 run 方法
super.run();
for (int i = 0; i < 100; i++) {
System.out.println( i + "." + this.name);
}
}

public void setMyThreadName(String name) {
this.name = name;
}
}

class MyThread2 implements Runnable { //好处是可以多继承
private String name;

@Override
public void run() { // 必须复写 run 方法
for (int i = 0; i < 100; i++) {
System.out.println( i + "." + this.name);
}
}

public void setMyThreadName(String name) {
this.name = name;
}
}

Callable 接口,返回值,名称,休眠

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.demo.callable;
import java.lang.management.ManagementFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableTest {
public static void main(String args[]) throws Exception {
FutureTask ticket = new FutureTask(new Ticket());
new Thread(ticket).start();
System.out.println(ticket.get()); // 线程的返回值

Mythread mt = new Mythread();
new Thread(mt, "线程y").start(); // 设置线程的名字
}
}

class Ticket implements Callable<String> { // 返回值类型是String

@Override
public String call() throws Exception { // 通过get方法获取返回值
for (int i = 0; i < 10; i++) {
System.out.println("卖了" + i + "张票");
}
return "票卖完了";
}
}

class Mythread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
Thread.sleep(1000); // 线程休眠1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i + "." + Thread.currentThread().getName()); // 获取线程的名字
}
}
}

线程锁

1
2