📄 thread_2.java
字号:
package thread4;
class TestThread {
public synchronized void execute(){ //synchronized 锁定的是对象 而不是类,参见:Thread_2.java。所以当有连个对象的不同的线程里边运行是,还是不能同步的!!!
for(int i=0;i<20;i++){ //如果要 锁定整个类,参见:thread_static_1。
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+Thread.currentThread().getName()+" "+i);
}
}
}
class ThreadA implements Runnable{
TestThread test=null;
public ThreadA(TestThread pTest){ //对象有外部引入,这样 在需要的时候, 可以 保证是同一个对象,当然也可以传入不同的实例。比如下面main()。
test=pTest;
}
public void run() {
test.execute();
}
}
public class Thread_2{
public static void main(String[] args){
TestThread test=new TestThread();//和下面的test2 生成不同的实例,也就要是 让两个线程 运行的是两个实例,再试验synchronized,
//证明了 public synchronized void execute() 锁定的是一个实例,而不是 整个类。
Runnable runabble=new ThreadA(test);
TestThread test2=new TestThread();//
Runnable runabble2=new ThreadA(test2);
Thread a=new Thread(runabble,"A");
a.start();
Thread b=new Thread(runabble2,"B");
b.start();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -