各位帮忙看看下面的代码,main方法中产生了几个线程,为什么?如果是多个线程,查看程序的运行结果,好像这个run方法被同步了啊?为什么啊。好像在后面三个线程中始终都无法访问index。
public class Interfacaesharethread {
public static void main(String[] args) {
Mythread1 mythread = new Mythread1();
Thread t1 = new Thread(mythread);
t1.start();
System.out.println(t1.getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t2 = new Thread(mythread);
t2.start();
System.out.println(t2.getName());
Thread t3 = new Thread(mythread);
t3.start();
System.out.println(t3.getName());
Thread t4 = new Thread(mythread);
t4.start();
System.out.println(t4.getName());
}
}class Mythread1 implements Runnable {
int index = 0; public synchronized void run() {
System.out.println("in to Thread");
while (index<10){
System.out.println(Thread.currentThread().getName()
+ "is running and the index is " + index++);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("out of Thread " + Thread.currentThread().getName());
}
}
public class Interfacaesharethread {
public static void main(String[] args) {
Mythread1 mythread = new Mythread1();
Thread t1 = new Thread(mythread);
t1.start();
System.out.println(t1.getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t2 = new Thread(mythread);
t2.start();
System.out.println(t2.getName());
Thread t3 = new Thread(mythread);
t3.start();
System.out.println(t3.getName());
Thread t4 = new Thread(mythread);
t4.start();
System.out.println(t4.getName());
}
}class Mythread1 implements Runnable {
int index = 0; public synchronized void run() {
System.out.println("in to Thread");
while (index<10){
System.out.println(Thread.currentThread().getName()
+ "is running and the index is " + index++);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("out of Thread " + Thread.currentThread().getName());
}
}
解决方案 »
- 在idea中创建文件夹问题
- applet客户端打印的问题
- 用HashSet时的一些问题?
- 动态联编
- 如何自动登录类似 tomcat的http://localhost:8080/manager/html 窗口提示的用户名和密码
- 小弟跪求一个ubb正则,希望大大们帮忙....在线等
- 怎么测试一个程序的运行时间?
- 如何让1000000(BigDecimal数据类型)格式化为1.000.1000(BigDecimal数据类型)
- 新手,请问在jsp页面中要用javabean,那javabean那段代码放在什么地方啊?是直接放在jsp页面中吗?
- 100分,请教如果配置JBoss的JMS
- 新浪微博开放api,想参与进去,有什么案例或者书参考?
- 书上的例子,有不明白的地方,麻烦解释下
t1.start();
System.out.println(t1.getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
第一个线程被启动以后主线程睡了两秒,等到再启动后面的线程以后第一个线程早就结束了
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
去掉再看看。
再请问如果是多个线程,各个线程中的同步方法会相互影响吗?
class Mythread1 implements Runnable {
int index = 0;public synchronized void run() { //run方法中的关键词:synchronized
System.out.println("in to Thread");
.....