欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java_多线程小练习

程序员文章站 2023-01-13 19:52:19
package com.fy.t1;/** * 创建线程2: * 1.实现Runnable接口 * 2.覆盖run()方法 * 3.创建实现类方法 * 4.创建线程对象 * @author z方圆 * */public class TestCreateThread {public static void main(String[] args) {MyRunnable mr = new MyRunnable();Thread t2 = new Thread(mr);...
package com.fy.t1;
/**
 * 创建线程2:
 * 1.实现Runnable接口
 * 2.覆盖run()方法
 * 3.创建实现类方法
 * 4.创建线程对象
 * @author z方圆
 *
 */

public class TestCreateThread {
	public static void main(String[] args) {
		MyRunnable mr = new MyRunnable();
		Thread t2 = new Thread(mr);
		t2.start();
	}
}

class MyRunnable implements Runnable {
	public void run() {
		for(int i = 0; i <= 50; i++) {
			System.out.println("MyRunnable : " +i);
		}
	}
}

package com.fy.t1;

public class TestThreadSafeQuestions {
	public static void main(String[] args) throws InterruptedException {
		String[] nums = new String[5];
		Thread t1 = new Thread(new Task1(nums));
		Thread t2 = new Thread(new Task2(nums));
		t1.start();
		t2.start();
		
		//两个线程共享堆中的同一个对象(地址)。各自是独自运行的
		Thread.sleep(5000);
		for(int i = 0; i < nums.length; i++) {
			System.out.println(nums[i] + "\t");
		}
	}
}

class Task1 implements Runnable{
	String[] nums;
	public Task1(String[] nums) {
		this.nums = nums;
	} 
	public void run() {
		synchronized(nums) {//对共享资源加锁,拿到锁才能执行原子操作
			System.out.println(Thread.currentThread().getName() + "拿到了锁,开始执行任务");
			try {
				Thread.sleep(5000);
			}catch(InterruptedException e) {
				
				e.printStackTrace();
				
			}
			//原子操作
			for(int i = 0; i < nums.length; i++) {
				
				if(nums[i] == null) {
					
					System.out.println(Thread.currentThread().getName()+"进来修改下标"+i);
					nums[i] = "Hello";
					break;
				}
			}
		}
	} 
}

class Task2 implements Runnable{
	String[] nums;
	public Task2(String[] nums) {
		this.nums = nums;
	}
		public void run() {
			synchronized(nums) {//对共享资源加锁!拿到锁,才能执行原子操作
				//原子操作
				System.out.println(Thread.currentThread().getName()+"拿到了锁,开始执行任务!");
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				for(int i = 0;i<nums.length;i++) {
					if(nums[i] == null) {
						System.out.println(Thread.currentThread().getName()+"进来修改下标"+i);
						nums[i] = "World";
						break;
				}
			}
		}
	}
}

本文地址:https://blog.csdn.net/zhu_fangyuan/article/details/107388821

相关标签: java第一阶段