请求一份多线程的代码样例。

mQney 2009-12-07 07:09:39
刚接触多线程,自己看了一点书,想写点东西,但是理论联系实际还有点困难,不知道方法和我需要实现的目的之间的联系,希望通过代码样例快速找到其中联系。

for(int i=0; i<100; i++){
System.out.println(i+1);
}

就是这段小程序,如何用5个线程实现。我的理解就是,有五个线程同时打印。
...全文
60 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
princess_rosie 2009-12-07
  • 打赏
  • 举报
回复
路过……
bawgiitx 2009-12-07
  • 打赏
  • 举报
回复
将第二个的
static int i = 0;
改为int i = 0;
就是第一个等价
bawgiitx 2009-12-07
  • 打赏
  • 举报
回复

/**每个线程各从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();
}
}
ikaoni 2009-12-07
  • 打赏
  • 举报
回复
要求每个线程都输出1-100,还是分别输出其中的不重复的数(并集是1-100)?
shine333 2009-12-07
  • 打赏
  • 举报
回复
public class Test extends Thread {

private final int num;

public Test(int num) {
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();
}
}

}

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧