有关JAVA中线程的问题

来源:百度知道 编辑:UC知道 时间:2024/05/13 09:22:02
本人JAVA初学者,请教两个有关JAVA中线程的问题。
1.线程的运行顺序。
JAVA中线程是抢占式的吗,是否同等优先级的线程抢着运行?对于单处理器,谁运气好谁就占用CPU? 一个线程执行完一个代码,也许立马被另一个线程抢占CPU执行一个代码,这样无规则的互相争夺着运 行?也就是说,单处理器在任意一个时刻,不可能有两个线程同时执行代码?多处理器呢?
比如下面的这个程序:

class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.
public void run() {
try {
a:for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class Th

①首先从main()开始,执行第一个语句new NewThread(),这里你就有误区,这里不是创建一个t或者Thread,Thread t; 这里就已经创建了,只不过它的值是null。

②从现在开始兵分两路。一方面,线程t开始运行,执行run()方法中的for循环a;另一方面,主线程跳转到main()的下一个语句,执行for循环b。

程序是上述这样运行的吗?如果是,for循环a和for循环b哪一个先执行,还是由于是相同优先级,争夺CPU碰运气?

Main Thread的优先级高于Child thread!所以说肯定是循环b先执行,而且执行完毕执行a,但因为有sleep所以才出现轮换输出的效果。

2.同步的用法。
synchronized(对象){

}

附运行结果:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Child Thread: 1
Main Thread: 3
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
写出我的运行结果告诉你,他不应该是固定的,他和cpu的处理速度又直接关系,sleep里面的单位是毫秒。