package thread;
/**
*
* @author Administrator
* JAVA中如果要同时执行两个方法则要用到多线程
* 本例中,要打印数字的同时也要打印字母,小例子
*/
public class TestThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread th1 = new PrintNum();
Thread th2 = new PrintChar();
th1.start();
th2.start();
}
}
//打印1-100的数字
class PrintNum extends Thread{
public void show(){
for (int i = 0; i <= 100; i++) {
System.out.print(i);
if(i%10 == 0)
System.out.println();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
show();
}
}
//打印a-z的字母
class PrintChar extends Thread{
public void show(){
for (int i = 65; i <= 90; i++) {
System.out.print((char)i);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
show();
}
}
例子二:泡茶例子,多线程主要是在烧水的同时可以洗杯子
package thread;
public class TestPaoCha {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("客人来了");
Water water = new Water();
water.start();
Washcup washcup = new Washcup();
washcup.start();
System.out.println("请喝茶");
}
}
//烧开水
class Water extends Thread{
public void burn(){
for (int i = 0; i <= 10; i++) {
System.out.println("正在烧水第" + i +"分钟");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("水烧开了");
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
this.burn();
}
}
//洗茶杯
class Washcup extends Thread{
public void wash(){
for (int i = 0; i <= 10; i++) {
System.out.println("正在洗第"+i+"个茶杯");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("茶杯都洗好了");
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
this.wash();
}
}
例子三:做饭,在炖汤的同时可以炒菜
package thread;
public class MakeFood {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread th1 = new MackeSoup();
Thread th2 = new MakeDish();
th1.start();
th2.start();
}
}
class MackeSoup extends Thread{
public void mackEggsoup(){
System.out.println("煮蛋蛋汤");
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("煮蛋蛋汤"+i+"分钟");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
this.mackEggsoup();
}
}
class MakeDish extends Thread{
public void makeDisk(){
System.out.println("正在煮菜");
for (int i = 1; i <= 4; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("正在煮第"+i+"个菜");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
this.makeDisk();
}
}