}classPrintNumOpt{intnum=0;intopt=0;intmaxNum=100;ReentrantLocklock=newReentrantLock();/** * 偶数 */Conditioncondition0=lock.newCondition();/** * 奇数 */Conditioncondition1=lock.newCondition();publicvoidprint0(){while(this.opt ==0) { lock.lock();try{for(; num < maxNum; num++) {...
{staticvoidMain(string[] args) {//创建两个线程,分别打印奇数和偶数PrintThread oddThread =newPrintThread(1,2,100); PrintThread evenThread=newPrintThread(0,2,100);//启动两个线程Thread t1 =newThread(oddThread.Run); Thread t2=newThread(evenThread.Run); t1.Start(); t2.Start();//等待两个...
方法1:自旋判断 开启两个线程,每个线程自旋判断当前值是奇数/偶数,然后打印 publicclassTest{volatilestaticinti=0;publicstaticvoidmain(String[]args){Threadthread1=newThread(()->{while(i<=100){if(i%2==0){System.out.println(i+"===偶数");i++;}}});Threadthread2=newThread(()->{while(i<=1...
usestd::thread;usestd::time::Duration;fnmain(){// 线程1lett1=thread::spawn(||{// 循环100次 偶数就打印否则使用 sleep 暂停当前线程foriin1..100{ifi%2==0{print!("偶线程: {} ",i);}else{thread::sleep(Duration::from_millis(1));}}});// 线程2lett2=thread::spawn(||{foriin1.....
两个线程交替打印输出数字,一个线程只打印偶数,另一个只打印奇数 这还不简单,直接用同步锁就可以解决,真的是这样吗? 撸起袖子就是干... synchronized 实现 publicclassTest01{privatestaticintcount;privatestaticfinalObjectlock=newObject();privatestaticfinalintnum=100;publicstaticvoidmain(String[]args){newThrea...
volatile static int flag = 0; public static void main(String[] args) { Thread myThread = new Thread(new myThread1()); Thread myThread2 = new Thread(new myThread2()); myThread.start(); myThread2.start(); } public static class myThread1 implements Runnable { ...
有两个线程odd和even, odd只打印偶数,even只打印奇数, 现在需要它们交替配合执行,按顺序打印出0~10: 这里采用java中的ReentrantLock和它对应的Condition来实现同步操作; 首先定义一个对象专门来做打印各种数字的操作: class OddEven { // 最后一个数字(比如0~100,maxNum = 100) ...
if ((count & 1) == 0) { System.out.println(Thread.currentThread().getName() + ":" + count++); } } } } }, "偶数线程").start(); new Thread(new Runnable() { @Override public void run() { while (count < 100) { synchronized (object) { ...
while(count <= 100 && count%2 == 0){ System.out.println(“偶数线程打印:”+count++); lock.notify(); if(count <= 100){ lock.wait(); } } } catch (InterruptedException e) { e.printStackTrace(); } } }; Runnable even = () -> { synchronized (lock) { try { while(count <= 10...
两个线程交替打印0——100的奇偶数(JAVA多线程) 使用两个线程去分别打印奇数和偶数,分别为奇数线程和偶数线程。 原理一是两个线程去竞争syn锁。 原理二是使用wait和notify方法来执行这个任务。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17