下面 Java 程序的输出结果可能是() class MyThread1 extends Thread {   public void run() {     Test.n1 = Test.n2;     Test.n2 = -1;   } } class MyThread2 extends Thread {   public void run() {     Test.n2 = Test.n1;     Test.n1 = -1;     System.out.printf(“%d %dn”, Test.n1, Test.n2);   } } public class Test {   public static int n1 = 0;   public static int n2 = 1;   public static void main(String[] args) {     MyThread1 t1 = new MyThread1();     MyThread2 t2 = new MyThread2();     t1.start();     t2.start();   } }

区块链毕设网qklbishe.com为您提供问题的解答

下面 Java 程序的输出结果可能是()

class MyThread1 extends Thread {    public void run() {     Test.n1 = Test.n2;     Test.n2 = -1;   } }  class MyThread2 extends Thread {    public void run() {     Test.n2 = Test.n1;     Test.n1 = -1;     System.out.printf("%d %dn", Test.n1, Test.n2);   } }  public class Test {    public static int n1 = 0;   public static int n2 = 1;    public static void main(String[] args) {     MyThread1 t1 = new MyThread1();     MyThread2 t2 = new MyThread2();     t1.start();     t2.start();   } }
正确答案:A、B、D 代码分析: 两个线程 t1 和 t2 并发执行,操作静态变量 n1 和 n2 ,由于线程执行顺序不确定,可能的结果如下:  t1 先执行完, t2 后执行:  t1 执行后: n1 = 1 ,  n2 = -1   t2 执行后: n2 = 1 ,  n1 = -1  → 输出  -1 1 (选项D)  t2 先执行完, t1 后执行:  t2 执行后: n2 = 0 ,  n1 = -1  → 输出  -1 0 (选项A)  t1 执行后: n1 = 0 ,  n2 = -1 (但输出已发生) 指令交错执行(竞态条件): 例如 t1 执行 Test.n1 = Test.n2 后, t2 执行全部操作,可能导致 n1 和 n2 均为 -1  → 输出  -1 -1 (选项B) 选项C( 1 1 )不可能出现,因为 n1 或 n2 最终至少有一个会被赋值为 -1
48:27

以上就是关于问题下面 Java 程序的输出结果可能是() class MyThread1 extends Thread {   public void run() {     Test.n1 = Test.n2;     Test.n2 = -1;   } } class MyThread2 extends Thread {   public void run() {     Test.n2 = Test.n1;     Test.n1 = -1;     System.out.printf(“%d %dn”, Test.n1, Test.n2);   } } public class Test {   public static int n1 = 0;   public static int n2 = 1;   public static void main(String[] args) {     MyThread1 t1 = new MyThread1();     MyThread2 t2 = new MyThread2();     t1.start();     t2.start();   } }的答案

欢迎关注区块链毕设网-
web3一级市场套利打新赚钱空投教程

区块链NFT链游项目方科学家脚本开发培训

从业7年-专注一级市场


微信:btc9767
TELEGRAM :https://t.me/btcok9

具体资料介绍

web3的一级市场千万收益的逻辑


进群点我



qklbishe.com区块链毕设代做网专注|以太坊fabric-计算机|java|毕业设计|代做平台-javagopython毕设 » 下面 Java 程序的输出结果可能是() class MyThread1 extends Thread {   public void run() {     Test.n1 = Test.n2;     Test.n2 = -1;   } } class MyThread2 extends Thread {   public void run() {     Test.n2 = Test.n1;     Test.n1 = -1;     System.out.printf(“%d %dn”, Test.n1, Test.n2);   } } public class Test {   public static int n1 = 0;   public static int n2 = 1;   public static void main(String[] args) {     MyThread1 t1 = new MyThread1();     MyThread2 t2 = new MyThread2();     t1.start();     t2.start();   } }