`

Thread common example

    博客分类:
  • Java
 
阅读更多

1.设计 4 个线程,其中两个线程每次对 j增加1,另外两个线程对j每次减少1。

public class ThreadTest {
	public static void main(String[] args) {
		MyThread thread = new MyThread();

		for (int i = 0; i < 2; i++) {
			Thread inc = new Thread(new Inc(thread));
			Thread dec = new Thread(new Dec(thread));

			inc.start();
			dec.start();
		}
	}
}

class MyThread {
	private int j;

	public synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName() + "-dec:" + j);
	}

	public synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName() + "-inc:" + j);
	}
}

class Dec implements Runnable {

	private MyThread obj;

	public Dec(MyThread obj) {
		this.obj = obj;
	}

	@Override
	public void run() {
		this.obj.dec();
	}
}

class Inc implements Runnable {

	private MyThread obj;

	public Inc(MyThread obj) {
		this.obj = obj;
	}

	@Override
	public void run() {
		this.obj.inc();
	}
}
 

2.设计两个线程,第一个线程从1加到10,在这加的过程中,第二个线程必须等待,当第一个线程加到10时,第二个线程启动,从10减到1,在这减的过程中,第一个线程必须等待,循环执行若干时间后,退出程序。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadTest {
	public static void main(String[] args) throws Exception {
		final Num num = new Num();
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new Runnable() {

			@Override
			public void run() {
				try {
					while (!Thread.interrupted()) {
						TimeUnit.MILLISECONDS.sleep(200);
						num.increased();
						num.waitForDecreasing();
					}
				} catch (InterruptedException e) {
					System.out.println("Exiting via interrupt");
				}
				System.out.println("Ending Increase");

			}
		});

		exec.execute(new Runnable() {

			@Override
			public void run() {
				try {
					while (!Thread.interrupted()) {
						num.waitForIncreasing();
						TimeUnit.MILLISECONDS.sleep(200);
						num.decreased();
					}
				} catch (InterruptedException e) {
					System.out.println("Exiting via interrupt");
				}
				System.out.println("Ending Decrease");

			}
		});

		TimeUnit.SECONDS.sleep(5); // Run for a while...
		exec.shutdownNow(); // Interrupt all tasks
	}
}

class Num {
	private boolean flag = false;
	private int i;

	public synchronized void increased() {
		flag = true;

		for (i = 1; i < 11; i++) {
			System.out.println(Thread.currentThread().getName() + "-inc " + i);
		}

		notifyAll();
	}

	public synchronized void decreased() {
		flag = false;

		for (i = 10; i > 0; i--) {
			System.out.println(Thread.currentThread().getName() + "-dec " + i);
		}

		notifyAll();
	}

	public synchronized void waitForIncreasing() throws InterruptedException {
		while (flag == false)
			wait();
	}

	public synchronized void waitForDecreasing() throws InterruptedException {
		while (flag == true)
			wait();
	}
}
分享到:
评论

相关推荐

    JavApi 0.8 发布,.NET 工具类库

    (Example for: Thread, Runnable, Socket, ServerSocket) SampleUsingChecksumClasses.cs: Using checksum classes. (Example for: Adler32, CRC32) SampleUsingCollection.cs: Using collection classes. (Example...

    一个开源的Java基础工具包

    四、线程相关工具类 1、com.baijob.commonTools.thread.BaseRunnable 此类实现了Runnable接口,扩展了功能。 增加名称、ID,调用次数和时间统计、线程停止接口等,并且在线程运行时,不允许此线程第二次启动。 2、...

    Using Perl For Web Programming.pdf

    Configuring Some Common Web Servers O'Reilly's WebSite H NCSA httpd H Apache H G Examining Some Other File- and Site-Administration Issues G From Here G Chapter 11 Database Interaction ...

    Keil.STM32F7xx_DFP.2.14.0.pack(STM32F7xx系列官方固件库驱动库板级支持包for Keil MDK 5)直接运行即可

    Version: 2.14.0 (2020-12-18) Keil.STM32F7xx_DFP.2.14.0.pack STM32CubeMX integration: Added support for USB PHY configuration (MX_...Reduced Idle and Timer thread stack size. Reworked README.md format.

    Keil.STM32F7xx_DFP.2.14.0.pack

    Version: 2.14.0 (2020-12-18) Keil.STM32F7xx_DFP.2.14.0.pack Download STM32CubeMX integration: Added support for USB PHY ...Reduced Idle and Timer thread stack size. Reworked README.md format.

    大名鼎鼎的 java2s 静态网页打包下载

    10. Thread 11. File 12. Generics 13. I18N 14. Swing 15. Swing Event 16. 2D Graphics 17. SWT 18. SWT 2D Graphics 19. Network 20. Database 21. Hibernate 22. JPA 23. JSP 24. JSTL 25. ...

    Mastering C# Concurrency

    Further, you'll learn about server scalability, asynchronous I/O, and thread pools, and write responsive traditional Windows and Windows Store applications. By the end of the book, you will be able ...

    Mastering.Csharp.Concurrency

    Further, you'll learn about server scalability, asynchronous I/O, and thread pools, and write responsive traditional Windows and Windows Store applications. By the end of the book, you will be able ...

    Professional C# 3rd Edition

    Thread Priorities 448 Synchronization 449 Summary 453 Chapter 16: Distributed Applications with .NET Remoting 455 What Is .NET Remoting? 456 Application Types and Protocols 456 CLR Object Remoting 457...

    python3.6.5参考手册 chm

    Common Stumbling Blocks Print Is A Function Views And Iterators Instead Of Lists Ordering Comparisons Integers Text Vs. Data Instead Of Unicode Vs. 8-bit Overview Of Syntax Changes New Syntax ...

    Java2核心技术卷I+卷2:基础知识(第8版) 代码

    Common Misconceptions about Java 11 Chapter 2: The Java Programming Environment 15 Installing the Java Development Kit 16 Choosing a Development Environment 21 Using the Command-Line Tools 22 ...

    微软内部资料-SQL性能优化3

    This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Describe locking ...

    ICS delphixe10源码版

    .\Samples Delphi Win32/Win64 common source for all demos .\Samples\delphi\BroswerDemo Delphi Win32/Win64 Web Browser sample application (all Delphi versions) .\Samples\delphi\BroswerDemo\Resources ...

    A盾电脑防护

    │ ├─example │ │ A-ProtectConsole.cpp │ │ A-ProtectConsole.h │ │ A-ProtectConsole.sln │ │ A-ProtectConsole.vcxproj │ │ Install.cpp │ │ Install.h │ │ KernelModule.h │ │ ntdll.lib │ ...

    OSGI in Action

    Avoiding common pitfalls 133 ■ Listening for services 136 Tracking services 141 4.4 Using services in the paint example 143 Defining a shape service 144 ■ Publishing a shape service 144 Tracking ...

    UNIX Network Programming Volume 1, Third Edition (Unix网络编程卷1第3版英文版)

    Protocol Usage by Common Internet Applications Section 2.14. Summary Exercises Part 2: Elementary Sockets Chapter 3. Sockets Introduction Section 3.1. Introduction Section 3.2. Socket...

    Embedded.Systems.2nd.Edition.1466468866.epub

    A system is comprised of components and interfaces connected together for a common purpose. Specific topics include microcontrollers, design, verification, hardware/software synchronization, ...

    微软内部资料-SQL性能优化2

    Before we look at how SQL Server uses and manages its memory, we need to ensure a full understanding of the more common memory related terms. The following definitions will help you understand how SQL...

    acpi控制笔记本风扇转速

    - Correctly initialize internal common FADT for all 64-bit "X" fields - Fixed a couple table mapping issues during table load - Fixed a couple alignment issues for IA64 - Initialize input array to ...

Global site tag (gtag.js) - Google Analytics