龙空技术网

java 使用三种方式实现线程顺序输出

小瓜瓜666 705

前言:

此刻小伙伴们对“java线程输出”大约比较着重,姐妹们都需要知道一些“java线程输出”的相关知识。那么小编也在网络上汇集了一些有关“java线程输出””的相关文章,希望姐妹们能喜欢,姐妹们快快来了解一下吧!

面试题:现在有两个线程t1和t2,t1输出1,t2输出2,两个线程同时启动,怎么让输出结果永远都是21;

1、wait / notify方式

package cn.itcast.n3;public class Test3 {				private static final Object obj = new Object();	private static boolean t2run = false;		public static void main(String[] args) {				Thread t1 = new Thread(() -> {			synchronized (obj) {				while (!t2run) {					try {						obj.wait();					} catch (InterruptedException e) {						e.printStackTrace();					}				}								System.out.println(Thread.currentThread().getName() + "线程打印:1");			}		},"t1") ;				Thread t2 = new Thread(() -> {			synchronized (obj) {				System.out.println(Thread.currentThread().getName() + "线程打印:2");				t2run = true;				obj.notify();			}		},"t2") ;						t1.start();		t2.start();			}}

2、await / signal方式

package cn.itcast.n3;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class Test4 {		private static ReentrantLock lock = new ReentrantLock();	private static boolean t2run = false;			public static void main(String[] args) {		Condition condition1 = lock.newCondition();				Thread t1 = new Thread(() -> {			lock.lock();			try {				while (!t2run) {					try {						condition1.await();					} catch (InterruptedException e) {						e.printStackTrace();					}				}								System.out.println(Thread.currentThread().getName() + "线程输出 1");							} finally {				lock.unlock();			}					},"t1") ;				Thread t2 = new Thread(() -> {			lock.lock();			try {				System.out.println(Thread.currentThread().getName() + "线程输出 2");				t2run = true;				condition1.signal();			} finally {				lock.unlock();			}		},"t2") ;								t1.start();		t2.start();	}}

3、park / unpark方式

package cn.itcast.n3;import java.util.concurrent.locks.LockSupport;public class Test5 {			public static void main(String[] args) {				Thread t1 = new Thread(() -> {			LockSupport.park();			System.out.println(Thread.currentThread().getName() + "线程输出 1");		},"t1") ;				Thread t2 = new Thread(() -> {			System.out.println(Thread.currentThread().getName() + "线程输出 2");			LockSupport.unpark(t1);		},"t2") ;				t1.start();		t2.start();			}}

标签: #java线程输出