刚接触多线程,自己看了一点书,想写点东西,但是理论联系实际还有点困难,不知道方法和我需要实现的目的之间的联系,希望通过代码样例快速找到其中联系。for(int i=0; i<100; i++){
System.out.println(i+1);
}就是这段小程序,如何用5个线程实现。我的理解就是,有五个线程同时打印。
System.out.println(i+1);
}就是这段小程序,如何用5个线程实现。我的理解就是,有五个线程同时打印。
解决方案 »
- IO小问题
- classloader的问题
- 求助!如何编写一个简单的JAVA Application 应用程序,计算e=1+1/1!+1/2!+1/3!+……1/20!,并输出计算结果。
- java 中,Bigdecimal 转 int 的 问题
- 新手请教:为什么我编译有的.java程序时报错找不到类?
- 如何把xdp转换成pdf文件.
- 谁碰到过这样的问题啊?怎么解决!!!分不够,我再加
- java 1.4中如何获取环境变量~!!~急~!
- 本人想练java,想找书中写的jdk1.2或1.4编译器,就是javac.exe。不要jbuild给具体网址
- weblogic 的疑问,请帮帮忙,谢谢
- 空指针异常
- AWT 问题 高手请进
this.num = num;
} @Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println((i + 1) + " in thread " + num);
try {
// 为了突出效果
sleep(10);
} catch (InterruptedException e) {
}
}
} public static void main(String[] args) throws Exception {
for (int i = 0; i < 5; i++) {
new Test(i).start();
}
}}
/**每个线程各从1打印到100
*/
public class Main{
public static void main(String[] args) throws Exception {
class runn implements Runnable { final String robj = ""; public void run() {
for (int i = 0; i < 100; i++) {
synchronized (robj) {
System.out.println("线程:" + Thread.currentThread() + ",i=" + (i + 1));
System.out.flush();
}
try {
Thread.sleep(0);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
runn r = new runn();
for (int i = 0; i < 5; i++) {
new Thread(r).start();
}
}
/**五线程加起来一共从1-100
*/
class runn implements Runnable { final String robj = "";
static int i = 0; public void run() {
for (; i < 100;) {
synchronized (robj) {
System.out.println("线程:" + Thread.currentThread() + ",i=" + (++i));
System.out.flush();
}
try {
Thread.sleep(0);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}public class Main { public static void main(String[] args) throws Exception { runn r = new runn();
for (int i = 0; i < 5; i++) {
new Thread(r).start();
}
}
static int i = 0;
改为int i = 0;
就是第一个等价