Java 的多线程
多线程的实现方法之一,用不同的类来实现接口Runnable,在类中重写run()方法
public class TaskClassDemo {
public static void main(String[] args) {
Runnable p1 = new PrintChar('a',100);//打印字母a一百次
Runnable p2 = new PrintChar('b',100);//打印字母b一百次
Runnable p3 = new PrintNUm(100);//打印1到100
Thread thread1 = new Thread(p1);
Thread thread2 = new Thread(p2);
Thread thread3 = new Thread(p3);
thread1.start();
thread2.start();
thread3.start();
}
}
class PrintChar implements Runnable{
private char charToPrint;
private int times;
public PrintChar(char charToPrint,int times)
{
this.charToPrint = charToPrint;//可以使用this关键字的方法
this.times = times;
}
public void run()
{
for(int i=0;i<100;i++)
{
System.out.println(charToPrint);
}
}
}
class PrintNUm implements Runnable{
private int lastNUm;
public PrintNUm (int lastNUm)
{
this.lastNUm = lastNUm;
}
public void run()
{
for(int i=0;i<=lastNUm;i++)
{
System.out.println(" "+i);
}
}
}