1.定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务。因此把run()方法称为执行体。
Thread thread = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:"+Thread.currentThread().getName());
}
}
};
thread.start();
2.定义runnable接口的实现类,并重写该接口的run()方法,该run()方法的方法体同样是该线程的线程执行体。
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2:"+Thread.currentThread().getName());
}
}
});
thread2.start();
}
案例:打印两个人的名字拼音,保证同一个人打印完,不受另一个的影响
public class TraditionalThreadSynchronnized {
public static void main(String[] args) {
new TraditionalThreadSynchronnized().init();
}
private void init() {
final OutPuter outputer = new OutPuter();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("pengyunle");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lichengli");
}
}
}).start();
}
class OutPuter{
public synchronized void output(String name) {
int len = name.length();
for(int i= 0;i<len;i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}