线程中run方法会被同步吗?

jiangkun_08 2010-08-09 11:06:44
各位帮忙看看下面的代码,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());
}
}
...全文
100 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Geek618 2010-08-09
  • 打赏
  • 举报
回复
run方法是被同步了,因为关键词:synchronized。
class Mythread1 implements Runnable {
int index = 0;

public synchronized void run() { //run方法中的关键词:synchronized
System.out.println("in to Thread");
.....


jiangkun_08 2010-08-09
  • 打赏
  • 举报
回复
楼上的不妨把
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
去掉再看看。
再请问如果是多个线程,各个线程中的同步方法会相互影响吗?
pengyingfu 2010-08-09
  • 打赏
  • 举报
回复
run方法没有同步只是应为
t1.start();
System.out.println(t1.getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
第一个线程被启动以后主线程睡了两秒,等到再启动后面的线程以后第一个线程早就结束了

62,614

社区成员

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

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