當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java LinkedBlockingQueue clear()用法及代碼示例


LinkedBlockingQueue的clear()方法從此隊列中刪除所有元素。應用此方法後,隊列將為空。

用法:

public void clear()

以下示例程序旨在說明LinkedBlockingQueue類的clear()方法:


示例1:

// Java Program Demonstrate clear() 
// method of LinkedBlockingQueue 
  
import java.util.concurrent.LinkedBlockingQueue; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // define capacity of LinkedBlockingQueue 
        int capacityOfQueue = 50; 
  
        // create object of LinkedBlockingQueue 
        LinkedBlockingQueue<Integer> linkedQueue 
            = new LinkedBlockingQueue<Integer>(capacityOfQueue); 
  
        // Add element to LinkedBlockingQueue 
        linkedQueue.add(2300); 
        linkedQueue.add(1322); 
        linkedQueue.add(8945); 
        linkedQueue.add(6512); 
  
        // print queue 
        System.out.println("LinkedBlockingQueue before using"
                           + " clear() : " + linkedQueue); 
  
        // Apply clear() method 
        linkedQueue.clear(); 
  
        // print queue 
        System.out.println(); 
        System.out.println("LinkedBlockingQueue after using"
                           + " clear() method : " + linkedQueue); 
    } 
}
輸出:
LinkedBlockingQueue before using clear() : [2300, 1322, 8945, 6512]

LinkedBlockingQueue after using clear() method : []

示例2:

// Java Program Demonstrate clear() 
// method of LinkedBlockingQueue 
  
import java.util.concurrent.LinkedBlockingQueue; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // define capacity of LinkedBlockingQueue 
        int capacityOfQueue = 50; 
  
        // create object of LinkedBlockingQueue 
        LinkedBlockingQueue<String> names 
            = new LinkedBlockingQueue<String>(capacityOfQueue); 
  
        // Add element to ArrayBlockingQueue 
        names.add("Shubham"); 
        names.add("Siddhant"); 
        names.add("Mahafuj"); 
        names.add("Arka"); 
        names.add("Raunak"); 
  
        // print queue 
        System.out.println("LinkedBlockingQueue before using"
                           + " clear() : " + names); 
  
        // Apply clear() method 
        names.clear(); 
  
        // print queue 
        System.out.println(); 
        System.out.println("LinkedBlockingQueue after using"
                           + " clear() method : " + names); 
    } 
}
輸出:
LinkedBlockingQueue before using clear() : [Shubham, Siddhant, Mahafuj, Arka, Raunak]

LinkedBlockingQueue after using clear() method : []

參考: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#clear–



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 LinkedBlockingQueue clear() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。