Java多线程基础使用(Thread|Runable|TimerTask&Timer)

Thread类

 

public class ThreadTest extends Thread { /** * @param learn how to use a Thread class */ private String ThreadName = ""; private int RandomSleepTime = 0; public ThreadTest(String ThreadName) { this.ThreadName = ThreadName; RandomSleepTime = (int) (Math.random() * 1000); } public void run() { //write what you want to do in here System.out.println(ThreadName + " START"); try { Thread.sleep(RandomSleepTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(ThreadName + " END"); } public static void main(String[] args) { // TODO Auto-generated method stub ThreadTest thread1 = new ThreadTest("THREAD1"); ThreadTest thread2 = new ThreadTest("THREAD2"); ThreadTest thread3 = new ThreadTest("THEEAD3"); thread1.start(); thread2.start(); thread3.start(); } }

 

Runnable类

public class RunnableTest implements Runnable { /** * @param learn how to use a Runnable interface */ private String RunnableName = ""; private int RandomSleepTime = 0; public RunnableTest(String RunnableName) { this.RunnableName = RunnableName; RandomSleepTime = (int) Math.random() * 1000; } @Override public void run() { // TODO Auto-generated method stub //write what you want to do in here System.out.println(RunnableName + " START"); try { Thread.sleep(RandomSleepTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(RunnableName + " END"); } public static void main(String[] args) { // TODO Auto-generated method stub RunnableTest runnable1 = new RunnableTest("RUNNABLE1"); RunnableTest runnable2 = new RunnableTest("RUNNABLE2"); RunnableTest runnable3 = new RunnableTest("RUNNABLE3"); new Thread(runnable1).start(); new Thread(runnable2).start(); new Thread(runnable3).start(); } }

 

TimerTask 和 Timer

import java.io.IOException; import java.util.Timer; import java.util.TimerTask; public class TimerTaskTest extends TimerTask { /** * @param args */ public TimerTaskTest() { } @Override public void run() { // TODO Auto-generated method stub System.out.println("TIME UP"); } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("TIME START"); Timer timer = new Timer(); timer.schedule(new TimerTaskTest(), 2000); boolean isStop = false; while (!isStop) { try {//input a c to terminate it int ch = System.in.read(); if (ch - 'c' == 0) { timer.cancel(); isStop = true; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

你可能感兴趣的:(Java多线程基础使用(Thread|Runable|TimerTask&Timer))