public class 多线程的错误演示 implements Runnable {
private int count =10;
public static void main(String[] arg){
Thread[] t = new Thread[6];
///////////////////////////////////
//继承接口Runnable会产生脏读现象 多线程的错误演示 tr = new 多线程的错误演示();
for(int i=0;i<3;i++){
t[i] = new Thread(tr);
t[i].setName("Runnable-->" + i);
t[i].start();
} ///////////////////////////////////
//继承类Thread,就不会产生脏读现象
for(int i=3;i<6;i++){
t[i] = new MyThread("Thread-->" + i);
t[i].start();
}
}
public void run() {
while (count>=0){
try{Thread.sleep(100);}catch(Exception e){;}
MyThread.p(Thread.currentThread().getName() + ":" + (count--));
}
}
}class MyThread extends Thread
{
private int count =10;
public MyThread(String name){
super(name);
} public void run(){
while (count>=0){
try{sleep(100);}catch(Exception e){;}
p(getName() + ":" + (count--));
}
} public static void p(String s){
System.out.println(s);
}
};
private int count =10;
public static void main(String[] arg){
Thread[] t = new Thread[6];
///////////////////////////////////
//继承接口Runnable会产生脏读现象 多线程的错误演示 tr = new 多线程的错误演示();
for(int i=0;i<3;i++){
t[i] = new Thread(tr);
t[i].setName("Runnable-->" + i);
t[i].start();
} ///////////////////////////////////
//继承类Thread,就不会产生脏读现象
for(int i=3;i<6;i++){
t[i] = new MyThread("Thread-->" + i);
t[i].start();
}
}
public void run() {
while (count>=0){
try{Thread.sleep(100);}catch(Exception e){;}
MyThread.p(Thread.currentThread().getName() + ":" + (count--));
}
}
}class MyThread extends Thread
{
private int count =10;
public MyThread(String name){
super(name);
} public void run(){
while (count>=0){
try{sleep(100);}catch(Exception e){;}
p(getName() + ":" + (count--));
}
} public static void p(String s){
System.out.println(s);
}
};
解决方案 »
- hibernateTemplate空指针
- 高效打印1000000次abc
- java基本数据类型以及编码标准的问题,求高手解答
- Tomcat经常自动关闭,出现EXCEPTION_ACCESS_VIOLATION (0xc0000005) jvm.dll错误
- oracle jdbc驱动问题
- SQL Server 2005 jdbc驱动
- 高手请快来救命,如何将同一个package下不同class的变量相互赋值
- HELP! 一个关于对象数组的小问题
- ClassPath问题,在线等待。。。
- public boolean Action在java1.3中已经废弃,有谁知道,在1.3中怎么办吗?
- 怎么才能让jdbc的驱动得到正确的加载?
- 怎樣把class打包成一個jar文件。就像jdk一些包一樣。謝謝~!
private int count =10;而在继承方式中,线程之间没有共享的成员,而是各线程各自有一个私有成员,即:
private int count =10;楼主的代码刚好是一个好例子,说明了何时需要考虑线程同步,并在一定程序上说明了怎样才能编写出线程安全的代码。在多线程环境中,当各线程不共享数据的时候,那么一定是线程安全的。问题是这种情况并不多见,在多数情况下需要共享数据,这时就需要进行适当的同步控制了。
就是一段代码同时只能有一个线程来操作
不然中间过程可能会产生不可预制的结果
而用synchronized的关键是建立一个monitor,这个monitor可以是要修改的variable也可以其他你认为合适的object比如method,然后通过给这个monitor加锁来实现线程安全,每个线程在获得这个锁之后,要执行完 load到workingmemory -> use&assign -> store到mainmemory 的过程,才会释放它得到的锁。这样就实现了所谓的线程安全。
另外当A线程执行此类的a()方法,另外当B线程执行此类的B()方法,同时a()及b()方法都会改变此类的private变量,这怎么能叫线程安全呢?
能具体解释一下volatile variable吗?