Java多线程,锁(synchronize),饿汉式单例线程,等待处理机制
生活随笔
收集整理的這篇文章主要介紹了
Java多线程,锁(synchronize),饿汉式单例线程,等待处理机制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一,禮讓和守護線程
package com.much.hard;public class TestYieldProtect {public static void main(String[] args) {Yield1 y1 = new Yield1();y1.setName("A");Yield2 y2 = new Yield2();y2.setName("B");//y1.start();//y2.start();Daemon1 d1 = new Daemon1();d1.setName("boss");Daemon2 d2 = new Daemon2();d2.setName("bodygGuard");d2.setDaemon(true);d1.start();d2.start();// d2 本來要打印500次的,d1打印10次,可它是守護線程,老板掛了,它也掛了。// 守護線程的終止是自身無法控制的,因此千萬不要把IO、File等重要操作邏輯分配給它;因為它不靠譜;// GC垃圾回收線程就是很好的例子。/* 當我們的程序中不再有任何運行的Thread,* 程序就不會再產生垃圾,垃圾回收器也就無事可做,* 所以當垃圾回收線程是JVM上僅剩的線程時,垃圾回收線程會自動離開。* 它始終在低級別的狀態中運行,用于實時監控和管理系統中的可回收資源。*/}}class Yield1 extends Thread {public void run() {for (int i = 0; i < 100; i++) {// 暫停當前正在執行的線程對象,并執行其他線程。讓多線程執行更和諧,而不是一人一次。if (i == 9) yield();System.out.println(getName() + "\t" + i);}} }class Yield2 extends Thread {public void run() {for (int i = 0; i < 100; i++) {System.out.println(getName() + "\t" + i);}} }class Daemon1 extends Thread {public void run() {for (int i = 0; i < 10; i++) {System.out.println(getName() + "\t" + i);}} }class Daemon2 extends Thread {public void run() {for (int i = 0; i < 500; i++) {System.out.println(getName() + "\t" + i);}} }禮讓 當A線程是9時,讓B線程執行。
二,加入線程
三,鎖
有了鎖,會讓一個線程結束后,執行下一個線程。。。
四,餓漢式單例
鎖機制的應用。
五,等待處理機制
package com.much.hard;public class TestWaiting {public static void main(String[] args) {// 等待喚醒機制。// 需求,我想用線程實現 1 2 1 2 1 2 1 2... 的循環。PrintTwo pt = new PrintTwo();Wait1 w1 = new Wait1(pt);Wait2 w2 = new Wait2(pt);w1.start();w2.start();}}class PrintTwo {int i = 1;public synchronized void print1() {if (i != 1) {try {this .wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(1);i = 2;// 喚醒下個線程。// notify是喚醒等待中的一個(隨機的)獲取對象鎖,進入可運行狀態,this.notify();}public synchronized void print2() {if (i == 1) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();} }System.out.println(2);i = 1;this.notify(); } }class Wait1 extends Thread {PrintTwo pt = null;public Wait1() {}public Wait1(PrintTwo pt) {this.pt = pt;}public void run() {while (true)pt.print1();} }class Wait2 extends Thread {PrintTwo pt = null;public Wait2() {}public Wait2(PrintTwo pt) {this.pt = pt;}public void run() {while (true)pt.print2();} }哈哈哈,初學線程,有點點懵,一下子太多了,我只是把老師講的小demo寫了一遍,應用還沒有基本。再此做下筆記。
總結
以上是生活随笔為你收集整理的Java多线程,锁(synchronize),饿汉式单例线程,等待处理机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 捕捉所有异常_详解Java中异常的分类
- 下一篇: java美元兑换,(Java实现) 美元