多线程编程中,最关键、最关心的问题应该就是同步问题,这是一个难点,也是核心。
在Java的多线程程序中,当多个程序竞争同一个资源时,为了防止资源的腐蚀,给第一个访问资源的线程分配一个对象锁,而后来者需要等待这个对象锁的释放。
Java线程的同步,最关心的是共享资源的使用。
先来了解一些有哪些线程的共享资源,从JVM中了解有哪些线程共享的数据是需要进行协调:
1,保存在堆中的实例变量;2,保存在方法区的类变量。
package thread_test;
/**
* 测试扩展Thread类实现的多线程程序
*
* @author ciding
* @createTime Dec 7, 2011 9:37:25 AM
*
*/
public class TestThread extends Thread{
private int threadnum;
public TestThread(int threadnum) {
this.threadnum = threadnum;
}
@Override
public synchronized void run() {
for(int i = 0;i<1000;i++){
System.out.println("NO." + threadnum + ":" + i );
}
}
public static void main(String[] args) throws Exception {
for(int i=0; i<10; i++){
new TestThread(i).start();
Thread.sleep(1);
}
}
}
[b]更多关于线程同步:[/b][url]http://ciding.iteye.com/blog/1306596[/url]
在Java的多线程程序中,当多个程序竞争同一个资源时,为了防止资源的腐蚀,给第一个访问资源的线程分配一个对象锁,而后来者需要等待这个对象锁的释放。
Java线程的同步,最关心的是共享资源的使用。
先来了解一些有哪些线程的共享资源,从JVM中了解有哪些线程共享的数据是需要进行协调:
1,保存在堆中的实例变量;2,保存在方法区的类变量。
package thread_test;
/**
* 测试扩展Thread类实现的多线程程序
*
* @author ciding
* @createTime Dec 7, 2011 9:37:25 AM
*
*/
public class TestThread extends Thread{
private int threadnum;
public TestThread(int threadnum) {
this.threadnum = threadnum;
}
@Override
public synchronized void run() {
for(int i = 0;i<1000;i++){
System.out.println("NO." + threadnum + ":" + i );
}
}
public static void main(String[] args) throws Exception {
for(int i=0; i<10; i++){
new TestThread(i).start();
Thread.sleep(1);
}
}
}
[b]更多关于线程同步:[/b][url]http://ciding.iteye.com/blog/1306596[/url]