`

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();
	}
}
分享到:
评论

相关推荐

    cuda_by_example

    - Libraries such as cuBLAS, cuFFT, and cuSPARSE provide optimized implementations of common algorithms. 9. **Multi-GPU and Distributed Computing** - CUDA supports multi-GPU configurations and ...

    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...

    CUDA-By-Example里的Julia修复包(patched)

    在这个修复包中,"common"文件夹可能包含了通用的CUDA库函数或工具,而"julia"文件夹则可能包含针对Julia迭代算子的修复或优化代码。Julia迭代是一种常见的科学计算和图像处理算法,它在复平面上进行迭代,用于生成...

    一个开源的Java基础工具包

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

    GPU高性能编程CUDA实战—book.h CPUBitmap.h等头文件

    CUDA编程的核心在于理解和运用CUDA的执行模型,包括线程块(thread blocks)、线程(threads)和网格(grids)的概念。开发者需要知道如何有效地组织这些线程单元,以便最大限度地利用GPU的并行性。此外,CUDA编程还...

    Introduction to MATLAB for Engineers

    - **7.1–1 Breaking Strength of Thread**: This section focuses on the statistical analysis of thread breaking strength, a common problem in textile engineering. It demonstrates the use of statistical ...

    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. ...

    使用Canal监听数据库配置时所报的异常记录

    在使用Canal监听MySQL数据库时,可能会遇到各种配置问题,导致Canal无法正常捕获数据库中的变更事件。这里我们分析并解决一个特定的异常情况,该情况发生在尝试监听数据库操作时,Canal无法获取到主库的状态信息。...

    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 ...

    PCL入门实例

    #include&lt;pcl/common/common_headers.h&gt; #include #include #include #include ``` 这里包含了必要的头文件,用于支持 I/O 操作、数据结构定义、可视化工具等。 ##### 2. 帮助函数 ```cpp void printUsage(const ...

    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 ...

    java英文笔试

    **Note**: This question is not directly related to technical knowledge but rather a common interview question. For the purpose of this document, we will focus on technical questions. #### 5. Please ...

    java 跑步移动的小人

    它主要包括了CLDC(Common Language Device Configuration)和CDC(Connected Device Configuration)两个配置,以及一系列用于不同设备的Profile。在这个案例中使用的主要是MIDP(Mobile Information Device Profile),...

    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 ...

Global site tag (gtag.js) - Google Analytics