java多线程之Thread VS Runnable

xiaoxiao2021-03-01  2

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效率高

转载请注明原文地址: https://www.6miu.com/read-3850260.html

最新回复(0)