1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 import java.util.concurrent.CountDownLatch; 18 import java.util.concurrent.TimeUnit; 19 20 public class Main { 21 static volatile boolean name_was_set = false; 22 static final String BIRTH_NAME = "birth name"; 23 static final String NEW_NAME = "new name"; 24 static final CountDownLatch child_started = new CountDownLatch(1); 25 26 private static class Child implements Runnable { 27 @Override run()28 public void run() { 29 String bname = Thread.currentThread().getName(); 30 if (!name_was_set && !bname.equals(BIRTH_NAME)) { 31 System.err.println("Wrong birth name: " + bname); 32 } 33 child_started.countDown(); 34 while (!name_was_set) { 35 try { 36 Thread.sleep(10); 37 } catch (InterruptedException e) { 38 System.out.println("Unexpected interrupt in child"); 39 } 40 } 41 System.out.println("Name was set"); 42 System.out.println("Final child Java name: " + Thread.currentThread().getName()); 43 System.out.print("Final child pthread name: "); 44 printPthreadName(); 45 } 46 } 47 main(String[] args)48 public static void main(String[] args) { 49 System.loadLibrary(args[0]); 50 System.out.print("Main Started; java name: "); 51 System.out.println(Thread.currentThread().getName()); 52 System.out.print("Pthread name: "); 53 printPthreadName(); 54 Thread t = new Thread(new Child(), BIRTH_NAME); 55 System.out.print("Child's Java name: "); 56 System.out.println(t.getName()); 57 t.start(); 58 try { 59 if (!child_started.await(2, TimeUnit.SECONDS)) { 60 System.out.println("Latch wait timed out"); 61 } 62 } catch (InterruptedException e) { 63 System.out.println("Unexpected interrupt in parent"); 64 } 65 System.out.println("Setting name from " + Thread.currentThread().getName()); 66 t.setName(NEW_NAME); 67 if (!t.getName().equals(NEW_NAME)) { 68 System.err.println("Wrong new name from main thread: " + t.getName()); 69 } 70 name_was_set = true; 71 try { 72 t.join(); 73 } catch (InterruptedException e) { 74 System.out.println("Unexpected interrupt in join()"); 75 } 76 System.out.println("Final parent Java name: " + Thread.currentThread().getName()); 77 System.out.print("Final parent pthread name: "); 78 printPthreadName(); 79 } 80 printPthreadName()81 private static native void printPthreadName(); 82 } 83