Java多线程(切换输入)

多线程


数组1 {1,2,3}

数组2{A,B,C}

要求切换输出结果:1A2B3C

package test_26;

import java.util.concurrent.locks.LockSupport;

class S1 {
	static Thread t1=null,t2=null;
	public static void main(String[] args) {
		char[] a1="123".toCharArray();
		char[] aC="ABC".toCharArray();
		t1=new Thread(()->{
			
			for(char c:a1) {
				System.out.print(c);
				LockSupport.unpark(t2);
				LockSupport.park();
			}
			
		},"t1");
		
	t2=new Thread(()->{
			
			for(char c:aC) {
				LockSupport.park();
				System.out.print(c);
				LockSupport.unpark(t1);
			}
			
		},"t2");
	t1.start();
	t2.start();
	}
}

方法二:一般的同步互斥锁

package test_26;

public class S2 {
	public static void main(String[] args) {
		final Object o=new Object();	
		
		char[] a1="123".toCharArray();
		char[] aC="ABC".toCharArray();
	//CountDownLatch	
		new Thread(()->{
			synchronized(o) {
				for(char c:a1) {
					System.out.print(c);
					try {
						o.notify();
						o.wait();
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				o.notify();
			}
		
		},"t1").start();
		
		new Thread(()->{
			synchronized(o) {
				for(char c:aC) {
					System.out.print(c);
					try {
						o.notify();
						o.wait();
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				o.notify();
			}
		
		},"t2").start();
	}
}
	

发布了112 篇原创文章 · 获赞 171 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43914278/article/details/104255154