list.stream().foreach()和list.foreach()的对比

转载https://baijiahao.baidu.com/s?id=1637952388544934539&wfr=spider&for=pc

1.简介

在java中有多种方式对集合进行遍历。本教程中将看两个类似的方法 Collection.stream().forEach()和Collection.forEach()。

在大多数情况下,两者都会产生相同的结果,但是,我们会看到一些微妙的差异。

2.概述

首先,创建一个迭代列表:

List<String> list = Arrays.asList("A","B","C","D");

最直接的方法是使用增强的for循环:

for(String s : list"){
	//something
}

如果我们想使用函数式Java,我们也可以使用forEach()。我们可以直接在集合上这样做:

Consumer<String> consumer = s -> {System.out::println};
list.forEach(consumer);

或者,我们可以在集合的流上调用forEach():

list.stream().forEach(consumer);

两个版本都将迭代列表并打印所有元素:

ABCD ABCD

在这个简单的例子中,我们使用的forEach()没有区别。

3.执行顺序

Collection.forEach()使用集合的迭代器(如果指定了一个),集合里元素的处理顺序是明确的。相反,Collection.stream().forEach()的处理顺序是不明确的。

在大多数情况下,我们选择上述两种方式的哪一种是没有区别的。但是有时候有。

3.1 Parallel Stream

并发流允许我们在多个线程中执行stream,在这种情况下,执行顺序也不明确的。Java只需要在调用任何最终操作(例如Collectors.toList())之前完成所有线程。

看一个例子,首先直接在集合上调用forEach(),然后在并发流上调用:

list.forEach(System.out::Println);
System.out.println(" ");
list.parallelStream().foreach(System.out::println);

如果我们多次运行代码,我们会看到list.forEach()以插入顺序处理元素,而 list.parallelStream().forEach()在每次运行会产生不同的结果。

一个可能的输出是:

ABCD CDBA

另一个是:

ABCD DBCA

3.2 自定义迭代器

让我们使用自定义迭代器定义一个列表,以反向顺序迭代集合:

class ReverseList extends ArrayList<String>{
	@Override
	public Iterator<String> iterator(){
		int startIndex = this.size()-1;
		List<String> list = this;
		
		Iterator<String> it = new Iterator<String>(){
			private int currentIndex;
			@Override
			public boolean hasNext(){
				return currentIndex >= 0;
			}
			
			@Override
			public String next(){
				String next = list.get(currentIndex);
				currentIndex--;
				return next;
			}
			
			@Override
			public void remove(){
				throw new UnsupportedOperationException();
			}
		};
		return it;
	}
}

当我们遍历列表时,再次使用forEach()直接在集合上,然后在流上:

List<String> myList = new ReverseList();
myList.addAll(list);
myList.forEach(System.out::Print);
System.out.println(" ");
myList.stream().forEach(System.out::print);

我们得到不同的结果:

DCBA ABCD

结果不同的原因是在列表中使用的forEach()会使用自定义迭代器,而stream().forEach()只是从列表中逐个获取元素,会忽略迭代器。

4.修改集合

很多集合在遍历的时候,不应该在结构上被修改(比如ArrayList或HashSet)。如果在迭代期间删除或添加元素,会抛出ConcurrentModification异常。

此外,集合设计为快速失败(fail-fast),这意味着一旦修改就抛出异常。

类似地,当我们在stream的执行期间添加或删除元素时,我们将得到ConcurrentModification异常。但是,异常将在稍后抛出。

两个forEach()方法之间的另一个细微差别是Java明确允许使用迭代器修改元素。相反,stream不能。

来看一下更详细的例子。

4.1 删除元素

定义一个列表,删除最后一个元素(“D”):

Consumer<String> removeElemet = s->{
	System.out.println(s + " " + list.size());
	if(s!=null && s.equals("A")){
		list.remove("D");
	}
}

遍历列表时,在打印第一个元素(“A”)后删除最后一个元素:

list.forEach(removeElement);

因为forEach()是快速失败的,所以我们停止迭代并在处理下一个元素之前看到异常:

A 4
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList.forEach(ArrayList.java:1252)
at ReverseList.main(ReverseList.java:1)

让我们看看如果我们使用stream().forEach()会发生什么:

list.stream().forEach(removeElement);

在这里,我们继续迭代整个列表,然后才看到异常:

A 4
B 3
C 3
null 3
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1380)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at ReverseList.main(ReverseList.java:1)

但是,Java并不保证会抛出ConcurrentModificationException。这意味着我们永远不应该编写依赖于此异常的程序。

4.2 改变元素

我们可以在迭代列表时更改元素:

list.forEach(e->{
	list.set(3,"E");
});

但是,虽然使用Collection.forEach()或stream()。forEach()执行此操作没有问题,但Java要求对流的操作是无干扰的。这意味着在执行流管道期间不应修改元素。

这背后的原因是流应该促进并行执行。在这里,修改流的元素可能会导致意外行为。

5.结论

在本文中,我们看到了一些示例,它们显示了Collection.forEach()和Collection.stream().forEach()之间的细微差别。

但是,重要的是要注意上面显示的所有示例仅仅是为了比较迭代集合的两种方式。

如果我们不需要流但只想迭代集合,则第一个选择应该直接在集合上使用forEach()。

  • 2
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<?php header("Content-Type: text/html; charset=UTF-8"); require("phpQuery.php"); $hj = QueryList::Query('http://mobile.csdn.net/',array("title"=>array('.unit h1','text'))); //dump($hj->data); $data = QueryList::Query('http://cms.querylist.cc/bizhi/453.html',array(     'image' => array('img','src')     ))->data; // $data = QueryList::Query('http://cms.querylist.cc/google/list_1.html',array(     'link' => array('a','href')     ))->data; $page = 'http://cms.querylist.cc/news/566.html'; $reg = array(     'title' => array('h1','text'),     'date' => array('.pt_info','text','-span -a',function($content){         $arr = explode(' ',$content);         return $arr[0];     }),     'content' => array('.post_content','html','a -.content_copyright -script',function($content){                   $doc = phpQuery::newDocumentHTML($content);             $imgs = pq($doc)->find('img');             foreach ($imgs as $img) {                 $src = 'http://cms.querylist.cc'.pq($img)->attr('src');                 $localSrc = 'w/'.md5($src).'.jpg';                 $stream = file_get_contents($src);                 file_put_contents($localSrc,$stream);                 pq($img)->attr('src',$localSrc);             }             return $doc->htmlOuter();     })     ); $rang = '.content'; $ql = QueryList::Query($page,$reg,$rang); $data = $ql->getData(); dump($data);支持抓取网站,进行爬虫,非常强大,是一个基于PHP的服务端开源项目,它可以让PHP开发人员轻松处理DOM文档内容,比如获取某新闻网站的头条信息。更有意思的是,它采用了jQuery的思想,你可以像使用jQuery一样处理页面内容,获取你想要的页面信息。
What’s Inside Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4th edition........................ 2 Changes .......................................... 3 Note on the cover design ....... 4 Acknowledgements ................ 4 Introduction 9 Prerequisites .......................... 9 Learning Java ....................... 10 Goals ..................................... 10 Teaching from this book ....... 11 JDK HTML documentation ...................... 11 Exercises ............................... 12 Foundations for Java ............ 12 Source code ........................... 12 Coding standards ......................... 14 Errors .................................... 14 Introduction to Objects 15 The progress of abstraction ........................ 15 An object has an interface ........................... 17 An object provides services ................... 18 The hidden implementation .................... 19 Reusing the implementation ................... 20 Inheritance............................ 21 Is-a vs. is-like-a relationships ......24 Interchangeable objects with polymorphism ............. 25 The singly rooted hierarchy .............................. 28 Containers ............................ 28 Parameterized types (Generics) ..29 Object creation & lifetime ... 30 Exception handling: dealing with errors ............... 31 Concurrent programming ... 32 Java and the Internet .......... 33 What is the Web? ......................... 33 Client-side programming ............ 34 Server-side programming ............ 38 Summary .............................. 38 Everything Is an Object 41 You manipulate objects with references ..................... 41 You must create all the objects ....................... 42 Where storage lives ...................... 42 Special case: primitive types ....... 43 Arrays in Java .............................. 44 You never need to destroy an object .................. 45 Scoping ........................................ 45 Scope of objects ........................... 46 Creating new data types: class ..................................... 46 Fields and methods ..................... 47 Methods, arguments, and return values ................. 48 The argument list ......................... 49 Building a Java program ...... 50 Name visibility ............................. 50 Using other components ............. 50 The static keyword ..................... 51 Your first Java program ....... 52 Compiling and running ............... 54 Comments and embedded documentation ..................... 55 Comment documentation ............ 55 Syntax .......................................... 56 Embedded HTML ........................ 56 Some example tags ...................... 57 Documentation example ............. 59 Coding style .......................... 60 Summary .............................. 60 Exercises .............................. 60 Operators 63 Simpler print statements ..... 63 Using Java operators ........... 64 Precedence ........................... 64 Assignment .......................... 65 Aliasing during method calls ....... 66 Mathematical operators....... 67 Unary minus and plus operators ....................... 68 Auto increment and decrement ............................ 69 Relational operators ............ 70 Testing object equivalence ........... 70 Logical operators .................. 71 Short-circuiting ............................ 72 Literals .................................. 73 Exponential notation ................... 74 Bitwise operators .................. 75 Shift operators ......................76 Ternary if-else operator ......79 String operator + and += .............................. 80 Common pitfalls when using operators ........... 81 Casting operators .................. 81 Truncation and rounding ........... 82 Promotion ................................... 83 Java has no “sizeof” ............. 83 A compendium of operators .......................... 84 Summary ............................... 91 Controlling Execution 93 true and false..................... 93 if-else .................................. 93 Iteration ............................... 94 do-while ..................................... 95 for ................................................ 95 The comma operator................... 96 Foreach syntax ......................97 return ................................. 99 break and continue .......... 99 The infamous “goto” ........... 101 switch ................................104 Summary ............................ 106 Initialization & Cleanup 107 Guaranteed initialization with the constructor ........... 107 Method overloading .......... 109 Distinguishing overloaded methods .................. 110 Overloading with primitives ....... 111 Overloading on return values .... 114 Default constructors ........... 114 The this keyword ............... 116 Calling constructors from constructors ...................... 118 The meaning of static ............... 119 Cleanup: finalization and garbage collection ........ 119 What is finalize() for? ............. 120 You must perform cleanup ......... 121 The termination condition ......... 121 How a garbage collector works .. 122 Member initialization ......... 125 Specifying initialization ............. 126 Constructor initialization ... 127 Order of initialization ................ 127 static data initialization ........... 128 Explicit static initialization ...... 130 Non-static instance initialization ................ 132 Array initialization ............. 133 Variable argument lists ............. 137 Enumerated types ............... 141 Summary ............................ 143 Access Control 145 package: the library unit ................... 146 Code organization ...................... 147 Creating unique package names ........................... 148 A custom tool library .................. 151 Using imports to change behavior ..................... 152 Package caveat ........................... 153 Java access specifiers .......... 153 Package access ........................... 153 public: interface access ............ 154 private: you can’t touch that! .. 155 protected: inheritance access . 156 Interface and implementation .......... 158 Class access ........................ 159 Summary ............................ 162 Reusing Classes 165 Composition syntax ........... 165 Inheritance syntax ............. 168 Initializing the base class ........... 169 Delegation ........................... 171 Combining composition and inheritance ................... 173 Guaranteeing proper cleanup .... 174 Name hiding ............................... 177 Choosing composition vs. inheritance .................... 178 protected ......................... 180 Upcasting ............................ 181 Why “upcasting”? ...................... 181 Composition vs. inheritance revisited ..................................... 182 The final keyword ............. 182 final data ................................... 183 final methods ............................ 186 final classes ............................... 187 final caution .............................. 188 Initialization and class loading ................ 189 Initialization with inheritance ... 189 Summary ............................. 191 Polymorphism 193 Upcasting revisited ............. 193 Forgetting the object type .......... 194 The twist ............................. 196 Method-call binding .................. 196 Producing the right behavior ..... 196 Extensibility ............................... 199 Pitfall: “overriding” private methods ...................... 202 Pitfall: fields and static methods .................. 203 Constructors and polymorphism ................... 204 Order of constructor calls ......... 204 Inheritance and cleanup ........... 206 Behavior of polymorphic methods inside constructors .... 210 Covariant return types ........ 211 Designing with inheritance .................. 212 Substitution vs. extension ......... 213 Downcasting and runtime type information ......... 215 Summary ............................. 217 Interfaces 219 Abstract classes and methods ....................... 219 Interfaces ........................... 222 Complete decoupling ......... 225 “Multiple inheritance” in Java ................................ 230 Extending an interface with inheritance .......................... 231 Name collisions when combining Interfaces ................233 Adapting to an interface .... 234 Fields in interfaces ............ 235 Initializing fields in interfaces .. 236 Nesting interfaces .............. 237 Interfaces and factories ..... 239 Summary ............................. 241 Inner Classes 243 Creating inner classes ........ 243 The link to the outer class .................... 244 Using .this and .new ........ 246 Inner classes and upcasting ..................... 247 Inner classes in methods and scopes ........... 249 Anonymous inner classes ........................ 251 Factory Method revisited .......... 254 Nested classes .................... 256 Classes inside interfaces ............ 257 Reaching outward from a multiplynested class ............... 259 Why inner classes? ............. 259 Closures & callbacks .................. 261 Inner classes & control frameworks ................... 263 Inheriting from inner classes ....................... 269 Can inner classes be overridden? ................... 269 Local inner classes .............. 271 Inner-class identifiers ........ 272 Summary ............................ 273 Holding Your Objects 275 Generics and type-safe containers ........... 276 Basic concepts .................... 278 Adding groups of elements ......................... 279 Printing containers ............ 281 List ..................................... 283 Iterator ............................. 286 ListIterator ............................ 288 LinkedList ....................... 289 Stack ................................. 291 Set ...................................... 292 Map ................................... 295 Queue ................................ 298 PriorityQueue ........................ 299 Collection vs. Iterator ... 301 Foreach and iterators ......... 304 The Adapter Method idiom ...... 306 Summary ............................ 308 Error Handling with Exceptions 313 Concepts ............................. 313 Basic exceptions.................. 314 Exception arguments ................. 315 Catching an exception ........ 315 The try block ............................. 316 Exception handlers .................... 316 Creating your own exceptions ................... 317 Exceptions and logging .............. 319 The exception specification ....................... 322 Catching any exception ..... 323 The stack trace .......................... 324 Rethrowing an exception ........... 325 Exception chaining .................... 327 Standard Java exceptions .......................... 330 Special case: RuntimeException ............... 330 Performing cleanup with finally ....................... 332 What’s finally for? .................... 333 Using finally during return .... 335 Pitfall: the lost exception .......... 336 Exception restrictions ....... 338 Constructors ...................... 340 Exception matching ........... 344 Alternative approaches ...... 345 History ...................................... 346 Perspectives ............................... 347 Passing exceptions to the console ............................ 349 Converting checked to unchecked exceptions ........... 350 Exception guidelines ......... 352 Summary ............................ 352 Strings 355 Immutable Strings ............355 Overloading ‘+’ vs. StringBuilder ................. 356 Unintended recursion ....... 359 Operations on Strings ....... 361 Formatting output ............. 362 printf() .................................... 363 System.out.format() ............ 363 The Formatter class ............... 363 Format specifiers ...................... 364 Formatter conversions ........... 366 String.format() ..................... 368 Regular expressions ........... 370 Basics .........................................370 Creating regular expressions ..... 372 Quantifiers ................................. 374 Pattern and Matcher ............. 375 split() ........................................382 Replace operations .................... 383 reset() .......................................384 Regular expressions and Java I/O .............................. 385 Scanning input ................... 386 Scanner delimiters ................. 388 Scanning with regular expressions ................... 389 StringTokenizer ............. 389 Summary ............................ 391 Type Information 393 The need for RTTI .............. 393 The Class object ................ 395 Class literals ............................... 399 Generic class references ............ 401 New cast syntax ........................ 403 Checking before a cast ....... 404 Using class literals .................... 409 A dynamic instanceof .............. 411 Counting recursively .................. 412 Registered factories ........... 413 instanceof vs. Class equivalence......................... 416 Reflection: runtime class information ................ 417 A class method extractor ........... 418 Dynamic proxies ................ 420 Null Objects ........................ 424 Mock Objects & Stubs ................ 429 Interfaces and type information ................ 430 Summary ............................ 436 Generics 439 Comparison with C++ ........ 440 Simple generics .................. 440 A tuple library ............................ 442 A stack class ............................... 444 RandomList ............................ 445 Generic interfaces .............. 446 Generic methods ................ 449 Leveraging type argument inference ...................450 Varargs and generic methods .... 452 A generic method to use with Generators............ 453 A general-purpose Generator . 453 Simplifying tuple use ................. 455 A Set utility................................ 456 Anonymous inner classes ....................... 459 Building complex models ................. 460 The mystery of erasure ...... 462 The C++ approach .................... 464 Migration compatibility ............ 466 The problem with erasure ......... 467 The action at the boundaries .... 468 Compensating for erasure ........................... 471 Creating instances of types ........ 472 Arrays of generics ...................... 475 Bounds ............................... 479 Wildcards ........................... 482 How smart is the compiler? ...... 484 Contravariance .......................... 485 Unbounded wildcards ............... 488 Capture conversion ................... 492 Issues ................................. 493 No primitives as type parameters .................... 493 Implementing parameterized interfaces ........... 495 Casting and warnings ............... 496 Overloading ............................... 498 Base class hijacks an interface .. 498 Self-bounded types ............ 500 Curiously recurring generics .... 500 Self-bounding ............................ 501 Argument covariance ................ 503 Dynamic type safety .......... 506 Exceptions ......................... 507 Mixins ................................ 509 Mixins in C++ ........................... 509 Mixing with interfaces ............... 510 Using the Decorator pattern ....... 511 Mixins with dynamic proxies .... 512 Latent typing ....................... 514 Compensating for the lack of latent typing ...... 518 Reflection ................................... 518 Applying a method to a sequence .............................. 519 When you don’t happen to have the right interface .......... 521 Simulating latent typing with adapters ............................. 523 Using function objects as strategies ....................... 526 Summary: Is casting really so bad? ...................... 531 Further reading .......................... 533 Arrays 535 Why arrays are special ........535 Arrays are first-class objects ............... 536 Returning an array ............. 539 Multidimensional arrays .................................. 540 Arrays and generics ........... 543 Creating test data ............... 546 Arrays.fill() ............................. 546 Data Generators ...................... 547 Creating arrays from Generators ..................... 551 Arrays utilities .................. 555 Copying an array ........................ 555 Comparing arrays ...................... 556 Array element comparisons ...... 557 Sorting an array .........................560 Searching a sorted array ............ 561 Summary ............................ 564 Containers in Depth 567 Full container taxonomy .... 567 Filling containers ............... 568 A Generator solution .............. 569 Map generators ......................... 570 Using Abstract classes ............. 573 Collection functionality ....................... 580 Optional operations ........... 582 Unsupported operations............ 583 List functionality ............... 586 Sets and storage order ...... 589 SortedSet ................................. 591 Queues ................................ 594 Priority queues ........................... 594 Deques ....................................... 595 Understanding Maps ........ 598 Performance .............................. 599 SortedMap ............................. 602 LinkedHashMap ................... 603 Hashing and hash codes .... 605 Understanding hashCodeQ .... 607 Hashing for speed ...................... 610 Overriding hashCode() ........... 613 Choosing an implementation .............. 617 A performance test framework ........................... 618 Choosing between Lists ............ 621 Microbenchmarking dangers .... 626 Choosing between Sets ............. 627 Choosing between Maps ........... 629 Utilities ............................... 632 Sorting and searching Lists ...... 635 Making a Collection or Map unmodifiable ............... 636 Synchronizing a Collection or Map ................... 637 Holding references ............ 639 The WeakHashMap .............. 640 Java 1.0/1.1 containers ...... 642 Vector & Enumeration ........ 642 Hashtable ............................... 643 Stack ........................................ 643 BitSet ....................................... 644 Summary ............................ 646 I/O 647 The File class .................... 647 A directory lister ........................ 647 Directory utilities ...................... 650 Checking for and creating directories ............. 654 Input and output ............... 656 Types of InputStream ............. 657 Types of OutputStream ......... 658 Adding attributes and useful interfaces .......... 659 Reading from an InputStream with FilterlnputStream ........ 660 Writing to an OutputStream with FilterOutputStream ...... 661 Readers & Writers ......... 662 Sources and sinks of data ......... 662 Modifying stream behavior ...... 663 Unchanged classes .................... 664 Off by itself: RandomAccessFile ....... 665 Typical uses of I/O streams .................... 665 Buffered input file ...................... 665 Input from memory .................. 666 Formatted memory input .......... 667 Basic file output ........................ 668 Storing and recovering data ..... 669 Reading and writing random-access files .................. 670 Piped streams ............................ 672 File reading & writing utilities ............... 672 Reading binary files ................... 674 Standard I/O ....................... 675 Reading from standard input .... 675 Changing System.out to a PrintWriter ...................... 676 Redirecting standard I/O .......... 676 Process control ................... 677 New I/O ............................. 679 Converting data.......................... 681 Fetching primitives ................... 684 View buffers ............................... 685 Data manipulation with buffers ............................... 688 Buffer details ............................. 689 Memory-mapped files ............... 692 File locking ................................. 695 Compression ...................... 698 Simple compression with GZIP .................................. 698 Multifile storage with Zip .......... 699 Java ARchives (JARs) ................ 701 Object serialization ............ 703 Finding the class ........................ 706 Controlling serialization ............ 707 Using persistence ....................... 713 XML .................................... 718 Preferences .......................... 721 Summary ............................ 722 Enumerated Types 725 Basic enum features ......... 725 Using static imports with enums ............................... 726 Adding methods to an enum ........................ 727 Overriding enum methods ....... 728 enums in switch statements ............. 728 The mystery of values() ........................ 729 Implements, not inherits ......................... 732 Random selection .............. 732 Using interfaces for organization .................. 734 Using EnumSet instead of flags ................... 737 Using EnumMap ............. 739 Constant-specific methods .............................. 740 Chain of Responsibility with enums ............................... 743 State machines with enums ..... 746 Multiple dispatching ........... 751 Dispatching with enums .......... 753 Using constant-specific methods ......... 755 Dispatching with EnumMaps ...................... 756 Using a 2-D array ....................... 757 Summary ............................ 759 Annotations 761 Basic syntax ....................... 762 Defining annotations ................. 762 Meta-annotations ...................... 763 Writing annotation processors ........ 765 Annotation elements ................. 765 Default value constraints ........... 766 Generating external files............ 766 Annotations don’t support inheritance ................... 769 Implementing the processor...... 769 Using apt to process annotations ............ 772 Using the Visitor pattern with apt .............................. 775 Annotation-based unit testing .......................... 778 Using @Unit with generics ....... 785 No “suites” necessary .................786 Implementing @Unit ............... 787 Removing test code .................... 792 Summary ............................. 795 Concurrency 797 The many faces of concurrency ....................... 798 Faster execution .........................798 Improving code design ............. 800 Basic threading .................. 801 Defining tasks ............................ 801 The Thread class ..................... 802 Using Executors ..................... 804 Producing return values from tasks ................................. 806 Sleeping ..................................... 808 Priority ...................................... 809 Yielding ...................................... 810 Daemon threads ......................... 810 Coding variations ....................... 814 Terminology ............................... 819 Joining a thread ......................... 819 Creating responsive user interfaces ............................ 821 Thread groups ........................... 822 Catching exceptions .................. 822 Sharing resources .............. 824 Improperly accessing resources ................... 825 Resolving shared resource contention ................... 827 Atomicity and volatility ............. 831 Atomic classes ........................... 836 Critical sections .......................... 837 Synchronizing on other objects .............................. 841 Thread local storage ..................843 Terminating tasks .............. 844 The ornamental garden ............ 844 Terminating when blocked ........ 847 Interruption .............................. 848 Checking for an interrupt .......... 854 Cooperation between tasks ..................... 856 wait() and notifyAll() ............ 857 notify() vs. notifyAll() ........... 861 Producers and consumers ........ 863 Producer-consumers and queues ................................ 868 Using pipes for I/O between tasks ............................. 872 Deadlock ............................. 874 New library components ........................ 879 CountDownLatch .................. 879 CyclicBarrier .......................... 881 DelayQueue ........................... 883 PriorityBlockingQueue....... 885 The greenhouse controller with ScheduledExecutor ...... 887 Semaphore ............................. 890 Exchanger .............................. 893 Simulation .......................... 896 Bank teller simulation .............. 896 The restaurant simulation ........ 900 Distributing work ..................... 904 Performance tuning ........... 909 Comparing mutex technologies ................... 909 Lock-free containers .................. 916 Optimistic locking...................... 922 ReadWriteLocks .................... 923 Active objects ..................... 925 Summary ............................ 929 Further reading .......................... 931 Graphical User Interfaces 933 Applets ............................... 935 Swing basics ....................... 935 A display framework .................. 937 Making a button ................. 938 Capturing an event ............. 939 Text areas ........................... 941 Controlling layout .............. 942 BorderLayout ......................... 942 FlowLayout ............................. 943 GridLayout .............................. 944 GridBagLayout....................... 944 Absolute positioning .................. 945 BoxLayout ............................... 945 The best approach? .................... 945 The Swing event model ..... 945 Event and listener types ........... 946 Tracking multiple events ........... 951 A selection of Swing components ............ 953 Buttons ....................................... 953 Icons .......................................... 955 Tool tips ..................................... 957 Text fields ................................... 957 Borders ....................................... 959 A mini-editor.............................. 959 Check boxes .............................. 960 Radio buttons ............................. 961 Combo boxes (drop-down lists) ...................... 962 List boxes .................................. 963 Tabbed panes ............................. 965 Message boxes ........................... 965 Menus ......................................... 967 Pop-up menus ............................ 972 Drawing ...................................... 973 Dialog boxes ............................... 975 File dialogs .................................978 HTML on Swing components .................... 980 Sliders and progress bars ......... 980 Selecting look & feel ................... 981 Trees, tables & clipboard .......... 983 JNLP and Java Web Start ................... 983 Concurrency & Swing ........ 988 Long-running tasks ................... 988 Visual threading ........................ 994 Visual programming and JavaBeans ................... 996 What is a JavaBean? ................. 996 Extracting Beanlnfo with the Introspector ............ 998 A more sophisticated Bean ..... 1002 JavaBeans and synchronization ....................... 1005 Packaging a Bean .................... 1008 More complex Bean support .. 1009 More to Beans .......................... 1010 Alternatives to Swing ........ 1010 Building Flash Web clients with Flex ................ 1011 Hello, Flex ................................. 1011 Compiling MXML .................... 1012 MXML and ActionScript.......... 1013 Containers and controls........... 1013 Effects and styles ..................... 1015 Events ....................................... 1016
Table of Contents Section 1 Introduction to SystemVerilog ...................................................................................................... 1 Section 2 Literal Values.................................................................................................................................. 4 2.1 Introduction (informative) ...............................................................................................................4 2.2 Literal value syntax..........................................................................................................................4 2.3 Integer and logic literals ..................................................................................................................4 2.4 Real literals ......................................................................................................................................5 2.5 Time literals .....................................................................................................................................5 2.6 String literals....................................................................................................................................5 2.7 Array literals ....................................................................................................................................6 2.8 Structure literals ...............................................................................................................................6 Section 3 Data Types....................................................................................................................................... 8 3.1 Introduction (informative) ...............................................................................................................8 3.2 Data type syntax...............................................................................................................................9 3.3 Integer data types ...........................................................................................................................10 3.4 Real and shortreal data types .........................................................................................................11 3.5 Void data type ................................................................................................................................11 3.6 chandle data type ...........................................................................................................................11 3.7 String data type ..............................................................................................................................12 3.8 Event data type...............................................................................................................................16 3.9 User-defined types .........................................................................................................................16 3.10 Enumerations .................................................................................................................................17 3.11 Structures and unions.....................................................................................................................22 3.12 Class...............................................................................................................................................26 3.13 Singular and aggregate types .........................................................................................................27 3.14 Casting ...........................................................................................................................................27 3.15 $cast dynamic casting ....................................................................................................................28 3.16 Bit-stream casting ..........................................................................................................................29 Section 4 Arrays ............................................................................................................................................ 32 4.1 Introduction (informative) .............................................................................................................32 4.2 Packed and unpacked arrays ..........................................................................................................32 4.3 Multiple dimensions ......................................................................................................................33 4.4 Indexing and slicing of arrays........................................................................................................34 4.5 Array querying functions ...............................................................................................................35 4.6 Dynamic arrays ..............................................................................................................................35 4.7 Array assignment ...........................................................................................................................37 4.8 Arrays as arguments.......................................................................................................................38 4.9 Associative arrays ..........................................................................................................................39 4.10 Associative array methods .............................................................................................................41 4.11 Associative array assignment.........................................................................................................44 4.12 Associative array arguments ..........................................................................................................44 4.13 Associative array literals................................................................................................................44 4.14 Queues ...........................................................................................................................................45 4.15 Array manipulation methods .........................................................................................................47 Section 5 Data Declarations ......................................................................................................................... 52 5.1 Introduction (informative) .............................................................................................................52 5.2 Data declaration syntax..................................................................................................................52 5.3 Constants........................................................................................................................................52 Accellera SystemVerilog 3.1a Extensions to Verilog-2001 viii Copyright 2004 Accellera. All rights reserved . 5.4 Variables ........................................................................................................................................53 5.5 Scope and lifetime .........................................................................................................................54 5.6 Nets, regs, and logic.......................................................................................................................55 5.7 Signal aliasing................................................................................................................................56 5.8 Type compatibility .........................................................................................................................58 Section 6 Attributes....................................................................................................................................... 61 6.1 Introduction (informative) .............................................................................................................61 6.2 Default attribute type .....................................................................................................................61 Section 7 Operators and Expressions.......................................................................................................... 62 7.1 Introduction (informative) .............................................................................................................62 7.2 Operator syntax..............................................................................................................................62 7.3 Assignment operators ....................................................................................................................62 7.4 Operations on logic and bit types ..................................................................................................63 7.5 Wild equality and wild inequality..................................................................................................63 7.6 Real operators ................................................................................................................................64 7.7 Size.................................................................................................................................................64 7.8 Sign ................................................................................................................................................64 7.9 Operator precedence and associativity ..........................................................................................64 7.10 Built-in methods ............................................................................................................................65 7.11 Static Prefixes ................................................................................................................................66 7.12 Concatenation ................................................................................................................................67 7.13 Unpacked array expressions ..........................................................................................................67 7.14 Structure expressions .....................................................................................................................68 7.15 Tagged union expressions and member access..............................................................................70 7.16 Aggregate expressions ...................................................................................................................71 7.17 Operator overloading .....................................................................................................................72 7.18 Streaming operators (pack / unpack) .............................................................................................73 7.19 Conditional operator ......................................................................................................................77 7.20 Set membership..............................................................................................................................77 Section 8 Procedural Statements and Control Flow.................................................................................. 79 8.1 Introduction (informative) .............................................................................................................79 8.2 Statements ......................................................................................................................................79 8.3 Blocking and nonblocking assignments ........................................................................................80 8.4 Selection statements.......................................................................................................................81 8.5 Loop statements .............................................................................................................................87 8.6 Jump statements.............................................................................................................................89 8.7 Final blocks....................................................................................................................................89 8.8 Named blocks and statement labels ...............................................................................................90 8.9 Disable ...........................................................................................................................................90 8.10 Event control..................................................................................................................................91 8.11 Level-sensitive sequence controls .................................................................................................93 8.12 Procedural assign and deassign removal .......................................................................................94 Section 9 Processes........................................................................................................................................ 95 9.1 Introduction (informative) .............................................................................................................95 9.2 Combinational logic.......................................................................................................................95 9.3 Latched logic..................................................................................................................................96 9.4 Sequential logic..............................................................................................................................96 9.5 Continuous assignments ................................................................................................................96 9.6 fork...join........................................................................................................................................97 9.7 Process execution threads ..............................................................................................................98 Accellera Extensions to Verilog-2001 SystemVerilog 3.1a Copyright 2004 Accellera. All rights reserved. ix 9.8 Process control ...............................................................................................................................98 9.9 Fine-grain process control ...........................................................................................................100 Section 10 Tasks and Functions................................................................................................................... 102 10.1 Introduction (informative) ...........................................................................................................102 10.2 Tasks ............................................................................................................................................103 10.3 Functions......................................................................................................................................104 10.4 Task and function argument passing ...........................................................................................106 10.5 Import and export functions.........................................................................................................109 Section 11 Classes.......................................................................................................................................... 111 11.1 Introduction (informative) ...........................................................................................................111 11.2 Syntax ..........................................................................................................................................112 11.3 Overview......................................................................................................................................113 11.4 Objects (class instance)................................................................................................................113 11.5 Object properties..........................................................................................................................114 11.6 Object methods ............................................................................................................................114 11.7 Constructors .................................................................................................................................115 11.8 Static class properties...................................................................................................................116 11.9 Static methods..............................................................................................................................116 11.10 This ..............................................................................................................................................116 11.11 Assignment, re-naming and copying ...........................................................................................117 11.12 Inheritance and subclasses ...........................................................................................................118 11.13 Overridden members....................................................................................................................119 11.14 Super ............................................................................................................................................119 11.15 Casting .........................................................................................................................................120 11.16 Chaining constructors ..................................................................................................................120 11.17 Data hiding and encapsulation .....................................................................................................121 11.18 Constant class properties .............................................................................................................121 11.19 Abstract classes and virtual methods ...........................................................................................122 11.20 Polymorphism: dynamic method lookup.....................................................................................123 11.21 Class scope resolution operator :: ................................................................................................123 11.22 Out of block declarations .............................................................................................................124 11.23 Parameterized classes ..................................................................................................................125 11.24 Typedef class ...............................................................................................................................126 11.25 Classes and structures ..................................................................................................................126 11.26 Memory management ..................................................................................................................127 Section 12 Random Constraints .................................................................................................................. 128 12.1 Introduction (informative) ...........................................................................................................128 12.2 Overview......................................................................................................................................128 12.3 Random variables ........................................................................................................................131 12.4 Constraint blocks .........................................................................................................................132 12.5 Randomization methods ..............................................................................................................145 12.6 In-line constraints — randomize() with.......................................................................................147 12.7 Disabling random variables with rand_mode() ...........................................................................148 12.8 Controlling constraints with constraint_mode() ..........................................................................149 12.9 Dynamic constraint modification.................................................................................................150 12.10 In-line random variable control ...................................................................................................150 12.11 Randomization of scope variables — std::randomize()...............................................................151 12.12 Random number system functions and methods .........................................................................153 12.13Random stability ..........................................................................................................................154 12.14 Manually seeding randomize .......................................................................................................156 12.15 Random weighted case — randcase ............................................................................................157 Accellera SystemVerilog 3.1a Extensions to Verilog-2001 x Copyright 2004 Accellera. All rights reserved . 12.16 Random sequence generation — randsequence...........................................................................158 Section 13 Interprocess Synchronization and Communication................................................................ 166 13.1 Introduction (informative) ...........................................................................................................166 13.2 Semaphores ..................................................................................................................................166 13.3 Mailboxes.....................................................................................................................................167 13.4 Parameterized mailboxes .............................................................................................................170 13.5 Event ............................................................................................................................................171 13.6 Event sequencing: wait_order() ...................................................................................................172 13.7 Event variables.............................................................................................................................173 Section 14 Scheduling Semantics................................................................................................................. 176 14.1 Execution of a hardware model and its verification environment ...............................................176 14.2 Event simulation ..........................................................................................................................176 14.3 The stratified event scheduler ......................................................................................................176 14.4 The PLI callback control points...................................................................................................180 Section 15 Clocking Blocks .......................................................................................................................... 181 15.1 Introduction (informative) ...........................................................................................................181 15.2 Clocking block declaration ..........................................................................................................181 15.3 Input and output skews ................................................................................................................183 15.4 Hierarchical expressions ..............................................................................................................184 15.5 Signals in multiple clocking blocks .............................................................................................185 15.6 Clocking block scope and lifetime...............................................................................................185 15.7 Multiple clocking blocks example ...............................................................................................185 15.8 Interfaces and clocking blocks.....................................................................................................186 15.9 Clocking block events..................................................................................................................187 15.10 Cycle delay: ## ............................................................................................................................187 15.11 Default clocking...........................................................................................................................188 15.12 Input sampling .............................................................................................................................189 15.13 Synchronous events .....................................................................................................................189 15.14 Synchronous drives......................................................................................................................190 Section 16 Program Block............................................................................................................................ 193 16.1 Introduction (informative) ...........................................................................................................193 16.2 The program construct .................................................................................................................193 16.3 Multiple programs........................................................................................................................195 16.4 Eliminating testbench races .........................................................................................................195 16.5 Blocking tasks in cycle/event mode.............................................................................................196 16.6 Program control tasks ..................................................................................................................196 Section 17 Assertions ................................................................................................................................... 198 17.1 Introduction (informative) ...........................................................................................................198 17.2 Immediate assertions....................................................................................................................198 17.3 Concurrent assertions overview...................................................................................................200 17.4 Boolean expressions ....................................................................................................................201 17.5 Sequences.....................................................................................................................................203 17.6 Declaring sequences ....................................................................................................................206 17.7 Sequence operations ....................................................................................................................208 17.8 Manipulating data in a sequence..................................................................................................224 17.9 Calling subroutines on match of a sequence................................................................................228 17.10 System functions..........................................................................................................................229 17.11 Declaring properties.....................................................................................................................229 17.12 Multiple clock support .................................................................................................................240 Accellera Extensions to Verilog-2001 SystemVerilog 3.1a Copyright 2004 Accellera. All rights reserved. xi 17.13 Concurrent assertions...................................................................................................................246 17.14 Clock resolution ...........................................................................................................................252 17.15 Binding properties to scopes or instances....................................................................................258 17.16 The expect statement ...................................................................................................................259 Section 18 Hierarchy..................................................................................................................................... 261 18.1 Introduction (informative) ...........................................................................................................261 18.2 Packages.......................................................................................................................................261 18.3 Compilation unit support .............................................................................................................265 18.4 Top-level instance........................................................................................................................266 18.5 Module declarations.....................................................................................................................267 18.6 Nested modules............................................................................................................................267 18.7 Extern modules ............................................................................................................................269 18.8 Port declarations ..........................................................................................................................270 18.9 List of port expressions................................................................................................................271 18.10 Time unit and precision ...............................................................................................................271 18.11 Module instances .........................................................................................................................272 18.12 Port connection rules ...................................................................................................................276 18.13 Name spaces ................................................................................................................................277 18.14 Hierarchical names ......................................................................................................................278 Section 19 Interfaces ..................................................................................................................................... 279 19.1 Introduction (informative) ...........................................................................................................279 19.2 Interface syntax............................................................................................................................280 19.3 Ports in interfaces.........................................................................................................................284 19.4 Modports ......................................................................................................................................285 19.5 Interfaces and specify blocks .......................................................................................................291 19.6 Tasks and functions in interfaces.................................................................................................291 19.7 Parameterized interfaces ..............................................................................................................297 19.8 Virtual interfaces..........................................................................................................................299 19.9 Access to interface objects...........................................................................................................303 Section 20 Coverage...................................................................................................................................... 305 20.1 Introduction (informative) ...........................................................................................................305 20.2 Defining the coverage model: covergroup...................................................................................306 20.3 Using covergroup in classes ........................................................................................................308 20.4 Defining coverage points .............................................................................................................309 20.5 Defining cross coverage...............................................................................................................315 20.6 Specifying coverage options ........................................................................................................319 20.7 Predefined coverage methods ......................................................................................................324 20.8 Predefined coverage system tasks and functions .........................................................................324 20.9 Organization of option and type_option members ......................................................................324 Section 21 Parameters .................................................................................................................................. 326 21.1 Introduction (informative) ...........................................................................................................326 21.2 Parameter declaration syntax .......................................................................................................327 Section 22 Configuration Libraries............................................................................................................. 330 22.1 Introduction (informative) ...........................................................................................................330 22.2 Libraries .......................................................................................................................................330 Section 23 System Tasks and System Functions ........................................................................................ 331 23.1 Introduction (informative) ...........................................................................................................331 23.2 Elaboration-time typeof function.................................................................................................331 Accellera SystemVerilog 3.1a Extensions to Verilog-2001 xii Copyright 2004 Accellera. All rights reserved . 23.3 Typename function ......................................................................................................................331 23.4 Expression size system function ..................................................................................................332 23.5 Range system function.................................................................................................................333 23.6 Shortreal conversions...................................................................................................................333 23.7 Array querying system functions .................................................................................................334 23.8 Assertion severity system tasks ...................................................................................................335 23.9 Assertion control system tasks.....................................................................................................336 23.10 Assertion system functions ..........................................................................................................336 23.11 Random number system functions...............................................................................................337 23.12 Program control ...........................................................................................................................337 23.13 Coverage system functions ..........................................................................................................337 23.14 Enhancements to Verilog-2001 system tasks ..............................................................................337 23.15 $readmemb and $readmemh........................................................................................................338 23.16 $writememb and $writememh .....................................................................................................338 23.17 File format considerations for multi-dimensional unpacked arrays ............................................339 23.18 System task arguments for multi-dimensional unpacked arrays .................................................340 Section 24 VCD Data .................................................................................................................................... 342 Section 25 Compiler Directives.................................................................................................................... 343 25.1 Introduction (informative) ...........................................................................................................343 25.2 ‘define macros..............................................................................................................................343 25.3 `include ........................................................................................................................................344 Section 26 Features under consideration for removal from SystemVerilog ........................................... 345 26.1 Introduction (informative) ...........................................................................................................345 26.2 Defparam statements....................................................................................................................345 26.3 Procedural assign and deassign statements..................................................................................345 Section 27 Direct Programming Interface (DPI) ....................................................................................... 347 27.1 Overview......................................................................................................................................347 27.2 Two layers of the DPI ..................................................................................................................348 27.3 Global name space of imported and exported functions..............................................................349 27.4 Imported tasks and functions .......................................................................................................349 27.5 Calling imported functions ..........................................................................................................355 27.6 Exported functions .......................................................................................................................356 27.7 Exported tasks..............................................................................................................................357 27.8 Disabling DPI tasks and functions...............................................................................................357 Section 28 SystemVerilog Assertion API .................................................................................................... 359 28.1 Requirements ...............................................................................................................................359 28.2 Extensions to VPI enumerations..................................................................................................359 28.3 Static information ........................................................................................................................360 28.4 Dynamic information ...................................................................................................................363 28.5 Control functions .........................................................................................................................366 Section 29 SystemVerilog Coverage API .................................................................................................... 368 29.1 Requirements ...............................................................................................................................368 29.2 SystemVerilog real-time coverage access ...................................................................................369 29.3 FSM recognition ..........................................................................................................................374 29.4 VPI coverage extensions..............................................................................................................377 Section 30 SystemVerilog Data Read API .................................................................................................. 381 30.1 Introduction (informative) ...........................................................................................................381 Accellera Extensions to Verilog-2001 SystemVerilog 3.1a Copyright 2004 Accellera. All rights reserved. xiii 30.2 Requirements ...............................................................................................................................381 30.3 Extensions to VPI enumerations..................................................................................................382 30.4 VPI object type additions.............................................................................................................383 30.5 Object model diagrams ................................................................................................................385 30.6 Usage extensions to VPI routines ................................................................................................387 30.7 VPI routines added in SystemVerilog .........................................................................................388 30.8 Reading data ................................................................................................................................389 30.9 Optionally unloading the data......................................................................................................399 30.10 Reading data from multiple databases and/or different read library providers ...........................399 30.11VPI routines extended in SystemVerilog.....................................................................................402 30.12VPI routines added in SystemVerilog .........................................................................................403 Section 31 SystemVerilog VPI Object Model............................................................................................. 407 31.1 Introduction (informative) ...........................................................................................................407 31.2 Instance .......................................................................................................................................409 31.3 Interface ......................................................................................................................................410 31.4 Program........................................................................................................................................410 31.5 Module (supersedes IEEE 1364-2001 26.6.1) ............................................................................411 31.6 Modport ......................................................................................................................................412 31.7 Interface tf decl ............................................................................................................................412 31.8 Ports (supersedes IEEE 1364-2001 26.6.5) .................................................................................413 31.9 Ref Obj.........................................................................................................................................414 31.10 Variables (supersedes IEEE 1364-2001 section 26.6.8) .............................................................416 31.11 Var Select (supersedes IEEE 1364-2001 26.6.8).........................................................................418 31.12 Typespec ......................................................................................................................................419 31.13 Variable Drivers and Loads (supersedes IEEE 1364-2001 26.6.23) ...........................................421 31.14 Instance Arrays (supersedes IEEE 1364-2001 26.6.2) ................................................................421 31.15 Scope (supersedes IEEE 1364-2001 26.6.3) ...............................................................................422 31.16 IO Declaration (supersedes IEEE 1364-2001 26.6.4) .................................................................423 31.17 Clocking Block ...........................................................................................................................424 31.18 Class Object Definition................................................................................................................425 31.19 Constraint, constraint ordering, distribution, ...............................................................................426 31.20 Constraint expression...................................................................................................................427 31.21 Class Variables ...........................................................................................................................428 31.23 Named Events (supersedes IEEE 1364-2001 26.6.11) ................................................................430 31.24 Task, Function Declaration (supersedes IEEE 1364-2001 26.6.18)............................................431 31.25 Alias Statement ...........................................................................................................................432 31.26 Frames (supersedes IEEE 1364-2001 26.6.20)............................................................................433 31.27 Threads.........................................................................................................................................434 31.28 tf call (supersedes IEEE 1364-2001 26.6.19) ..............................................................................435 31.29 Module path, path term (supersedes IEEE 1364-2001 26.6.15) .................................................436 31.30 Concurrent assertions ..................................................................................................................437 31.31 Property Decl ..............................................................................................................................437 31.32 Property Specification .................................................................................................................438 31.33 Multiclock Sequence Expression ................................................................................................439 31.34 Sequence Declaration .................................................................................................................440 31.35 Sequence Expression ..................................................................................................................441 31.36 Attribute (supersedes IEEE 1364-2001 26.6.42) ........................................................................442 31.37 Atomic Statement (supersedes IEEE 1364-2001 26.6.27) .........................................................443 31.38 If, if else, return, case, do while (supersedes IEEE 1364-2001 26.6.35, 26.6.36).......................444 31.39 waits, disables, expect, foreach (supersedes IEEE 1364 26.6.38) ...............................................445 31.40 Simple expressions (supersedes IEEE 1364-2001 26.6.25) ........................................................446 31.41 Expressions (supersedes IEEE 1364-2001 26.6.26) ....................................................................447 31.42 Event control (supersedes IEEE 1364-2001 26.6.30)..................................................................448 Accellera SystemVerilog 3.1a Extensions to Verilog-2001 xiv Copyright 2004 Accellera. All rights reserved . 31.43 Event stmt (supersedes IEEE 1364-2001 26.6.27) .....................................................................448 31.44 Process (supersedes IEEE 1364-2001 26.6.27) ..........................................................................449 31.45 Assignment (supersedes IEEE 1364-2001 26.6.28) ...................................................................449 Annex A Formal Syntax.............................................................................................................................. 451 Annex B Keywords ...................................................................................................................................... 488 Annex C Std Package ................................................................................................................................. 490 Annex D Linked Lists................................................................................................................................. 492 Annex E DPI C-layer .................................................................................................................................. 498 Annex F Include files .................................................................................................................................. 523 Annex G Inclusion of Foreign Language Code ......................................................................................... 529 Annex H Formal Semantics of Concurrent Assertions ............................................................................ 533 Annex I sv_vpi_user.h................................................................................................................................ 544 Annex J Glossary ........................................................................................................................................ 553 Annex K Bibliography................................................................................................................................. 555 Index 557

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值