多线程也叫并发在以前的单核处理器 实际上并不是真正的实现了多线程 而是分时间片各自来运行的现在的双核就可以真正的实现多线程操作了
例子:
public class ThreadTest { public static void main(String[] args) { Thread thread1 = new Thread(new Counter()); thread1.start(); Thread thread2 = new Thread(new Counter()); thread2.start(); }}class Counter implements Runnable { int taskCount = 0; public synchronized void leftOff() { while (taskCount < 20) { System.out.println("[" + Thread.currentThread().getName() + "] is the " + taskCount++); } } public void run() { leftOff(); }}如上,两个线程thread1和thread2同时运行,得用start方法调用Counter 类中的run方法,在自增时,只要少于20就打印System.out.println("[" + Thread.currentThread().getName()+ "] is the " + taskCount++);
|