继承Thread创建线程
public class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name=name;
}
@Override
public void run(){
while (true){
System.out.println("The Thread Name is:"+name);
}
}
public static void main(String[] args) {
MyThread m1=new MyThread("AS");
MyThread m2=new MyThread("sad");
m1.start();
m2.start();
}
}
加上sleep
public class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name=name;
}
@Override
public void run(){
while (true){
try{
sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("The Thread Name is:"+name);
}
}
public static void main(String[] args) {
MyThread m1=new MyThread("AS");
MyThread m2=new MyThread("sad");
m1.start();
m2.start();
}
}
实现Runnable接口
import static java.lang.Thread.sleep;
public class MyThread implements Runnable{
private static int count=0;
@Override
public void run(){
while (true){
try{
count++;
sleep(100);
System.out.println("The Counter is:"+count);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread m=new MyThread();
Thread t1=new Thread(m);
Thread t2=new Thread(m);
t1.start();
t2.start();
}
}
方法同步
import static java.lang.Thread.sleep;
public class MyThread implements Runnable{
private static int count=0;
@Override
public void run(){
while (true){
try{
synchronized(this){
count++;
sleep(100);
System.out.println("The Counter is:"+count);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread m=new MyThread();
Thread t1=new Thread(m);
Thread t2=new Thread(m);
t1.start();
t2.start();
}
}