小猪又回来了~
其实我一直都在,哈哈哈,只是没什么时间写博客
那现在就总结一下自己最近的做学吧!

这些内容都是小猪自己学习之后的总结的,如果哪里有错的,希望大佬指出哈~

那现在就进入正题吧!这篇博客要写的是Thread类的基本用法
我们都知道使用最多的线程创建的方法是使用lambda表达式创建,那现在我们来看看其他的方法吧!这里有五种线程创建的方法~
(1)继承Thread ,重写run
例如:
class MyThread extends Thread{
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
}
}
public class Demo21 {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
t.run();
while (true) {
System.out.println("hello main");
try {
Thread.sleep(1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
}
}
(2)实现 Runnable, 重写 run
例子:
class MyRunnable implements Runnable{
@Override
public void run() {
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
}
}
public class Demo22 {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
while (true){
System.out.println("hello main");
try {
Thread.sleep(1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
}
}
(3)继承 Thread, 重写 run, 使用匿名内部类
例子:
public class Demo23 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
}
};
t.start();
}
}
(4)实现 Runnable, 重写 run, 使用匿名内部类
例子:
public class Demo24 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
}
(5)使用 lambda 表达式
例子:
public class Demo25 {
public static void main(String[] args) {
Thread t = new Thread(() ->{
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
});
t.start();
}
}
以上就是五种创建线程的方法以及例子
总的来说,分为两大类:继承Thread类和实现Runnable接口。
目前常见的线程中断有两种方法:通过共享的标志来进行沟通和通过调用interrupt()方法来通知
这个操作需要给关键字上加volatile
例子:
public volatile boolean isQuit = false
其中Thread内部包含了一个Boolean类型的变量作为线程是否被中断的标志,如下:

(如果想要代码示例的可以来私我哦~)
等待线程的方法:

上面的代码中也有用到,这里就不详细举例了~
方法和说明:

上面代码中也用过了~就不详细讲了!
方法:
public static Thread currentThread();
说明:
返回当前线程的对象引用
代码实例:
Thread thread = Thread.currentThread();

以上内容只是简单的讲述,如果又哪里你有疑惑但这里没讲到的,欢迎来骚扰哈~
拜~
记得关注小猪哦!
