62,615
社区成员
发帖
与我相关
我的任务
分享
/**每个线程各从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();
}
}