标题: 多线程问题 [打印本页] 作者: 臧盼 时间: 2012-12-10 20:36 标题: 多线程问题 class MyThread implements Runnable
{
private int num = 0 ;
public void run(){
for(int i = 0;i<10;i++){
try{
Thread.sleep(20) ;
}catch(Exception e){}
System.out.println(num++) ;
}
}
}
public class RunnableDemo
{
public static void main(String[] args){
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt) ;
Thread t2 = new Thread(mt) ;
Thread t3 = new Thread(mt) ;
Thread t4 = new Thread(mt) ;
class MyThread implements Runnable
{
private int num = 0 ;
public synchronized void run(){//这里存在线程安全问题,需要加上同步。同步函数或者同步代码块
for(int i = 0;i<10;i++){
try{
Thread.sleep(20) ;
}catch(Exception e){}
System.out.println(num++) ;
}
}
}
public class RunnableDemo
{
public static void main(String[] args){
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt) ;
Thread t2 = new Thread(mt) ;
Thread t3 = new Thread(mt) ;
Thread t4 = new Thread(mt) ;
作者: 小洋人最happy 时间: 2012-12-10 20:57
class MyThread implements Runnable
{
private int num = 0 ;
public void run(){
while(true){ //此处加上个判断循环条件就可以了
for(int i = 0;i<10;i++){
try{
Thread.sleep(20) ;
}catch(Exception e){}
System.out.println(num++) ;
}
}
}
}
public class RunnableDemo
{
public static void main(String[] args){
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt) ;
Thread t2 = new Thread(mt) ;
Thread t3 = new Thread(mt) ;
Thread t4 = new Thread(mt) ;
class MyThread implements Runnable
{
private int num = 0 ;
Object obj =new Object();
public void run()
{
synchronized(obj)
{
for(int i = 0;i<10;i++){
try{
Thread.sleep(20) ;
}
catch(Exception e)
{}
System.out.println(Thread.currentThread().getName()+"::"+num++) ;
}
}
}
}
class RunnableDemo
{
public static void main(String[] args){
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt) ;
Thread t2 = new Thread(mt) ;
Thread t3 = new Thread(mt) ;
Thread t4 = new Thread(mt) ;
t1.start() ;
t2.start() ;
t3.start() ;
t4.start() ;
}
} 作者: 李培根 时间: 2012-12-11 09:16
class MyThread implements Runnable
{
private int num = 0 ;
public synchronized void run(){//这里存在线程安全问题,需要加上同步。同步函数或者同步代码块
for(int i = 0;i<10;i++){
try{
Thread.sleep(20) ;
}catch(Exception e){}
System.out.println(num++) ;
}
}
}
public class RunnableDemo
{
public static void main(String[] args){
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt) ;
Thread t2 = new Thread(mt) ;
Thread t3 = new Thread(mt) ;
Thread t4 = new Thread(mt) ;