java多线程之Thread VS Runnable
程序员文章站
2022-05-05 22:45:28
...
0.线程的生命周期
1.java实现多线程方式一:
2.java实现多线程方式二:
3.两种方式的比较:
package ThreadCompare;
public class MyThreadByRunnable implements Runnable {
private int ticket = 5;
@Override
public void run() {
while(ticket>0) {
ticket--;
System.out.println(
MyThreadByThread.currentThread().getName()+"卖了1张票,还剩"+ticket+"张");
}
}
}
package ThreadCompare;
public class MyThreadByThread extends Thread {
private int ticket = 5;
@Override
public void run() {
while(ticket>0) {
ticket--;
System.out.println(
MyThreadByThread.currentThread().getName()+"卖了1张票,还剩"+ticket+"张");
}
}
}
package ThreadCompare;
import java.util.Scanner;
public class MainTest {
public void testThread() {
MyThreadByThread mt1 = new MyThreadByThread();
MyThreadByThread mt2 = new MyThreadByThread();
MyThreadByThread mt3 = new MyThreadByThread();
mt1.start();
mt2.start();
mt3.start();
}
public void testRunnable() {
MyThreadByRunnable mt = new MyThreadByRunnable();
Thread t1 = new Thread(mt,"窗口1");
Thread t2 = new Thread(mt,"窗口2");
Thread t3 = new Thread(mt,"窗口3");
t1.start();
t2.start();
t3.start();
}
public void demonThreadTest() {
System.out.println("*********主线程开始执行了*********");
DemonThread dt = new DemonThread();
Thread t = new Thread(dt,"demon");
t.setDaemon(true);
t.start();
Scanner sc = new Scanner(System.in);
sc.next();
System.out.println("*********主线程执行结束了*********");
}
public static void main(String[] args) {
//new MainTest().testThread();
//new MainTest().testRunnable();
new MainTest().demonThreadTest();
}
}
执行new MainTest().testRunnable()结果
执行new MainTest().testThread()结果
所以:
Runnable方式可以避免java单继承带来的缺陷,想实现就直接实现接口即可
Runnable实现的线程都是可以由该接口来进行连接,适用于多个线程处理同一个Runnable对象的情况
4.守护线程
Runnable实现方式设置守护线程
通过setDemon(true)方法实现(代码如上所示)。
package ThreadCompare;
public class DemonThread implements Runnable {
private int count = 0;
@Override
public void run() {
System.out.println("*********守护线程开始执行了*********");
while (count<100) {
count++;
System.out.println("线程执行了 "+count+" 次");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("*********守护线程执行结束了*********");
}
}
守护线程:
5.线程同步—synchronized用法
分析:
给方法加synchronized 会使得整个方法都是在锁保护(或者叫同步控制)之内,当方法较为冗长时开销较大
只给特定代码块添加synchronized效率高
推荐阅读
-
JAVA多线程Thread和Runnable的实现
-
浅谈Java线程Thread之interrupt中断解析
-
Android开发笔记之:Handler Runnable与Thread的区别详解
-
Java多线程同步工具类之Semaphore
-
Java多线程系列--“JUC锁”06之 Condition条件
-
Java线程Thread的状态解析以及状态转换分析 多线程中篇(七)
-
Java中实现多线程继承Thread类与实现Runnable接口的区别
-
Java多线程Part3:线程(Thread)的状态和等待唤醒机制
-
java多线程学习之从正常到自残
-
Java的Thread,Runnable、Callable、Future、FutureTask、Executors,ExecutorService