【Java】Java多线程的简单使用
import java.util.*; public class ThreadsTest extends Thread{ private String name; private int time; public ThreadsTest(int time,String name){ this.time = time; this.name = name; } public void run() { while (true) { try { System.out.println(name+":"+Calendar.getInstance().getTime()); Thread.sleep(time); }catch(InterruptedException e) {} } } public static void main(String[] args) { ThreadsTest fast = new ThreadsTest(1000,"Fast"); ThreadsTest slow = new ThreadsTest(3000,"Slow"); fast.start(); slow.start(); } }
效果如图:
有临界资源,用synchronized修饰代码块或方法,可实现某一时刻只有一个线程拥有对象锁
以堆栈举例:
public class Stack{ int idx = 0; char[] data = new char[10]; public void push(char c) { synchronized (this) { //方法一,用在代码块 data[idx] = c; idx++; } } public synchronized char pop() { //方法二,用在描述对象 idx--; return data[idx]; } }
wait()方法和notify()方法,wait()方法使线程进入阻塞状态,释放占用的对象锁。notify()方法和notifyAll()方法,前者随机唤醒等待中的一个线程,后者使等待队列中的全部线程解除阻塞。
实现Runnable接口
class TimePrinter implements Runnable{ //此处省略代码,只有构造对象时候不同 public static void main(String[] args) { Thread fast = new Thread(new TimePrinter(1000,"Fast")); Thread slow = new Thread(new TimePrinter(1000,"slow")); fast.start(); slow.start(); } }