public class MyThread extends Thread { public void run() { // code to be executed in this thread } } // creating and starting a new thread MyThread thread = new MyThread(); thread.start();
public class Counter { private int count = 0; public synchronized void increment() { count++; } public int getCount() { return count; } } // creating two threads that increment a shared counter Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); t1.start(); t2.start(); // wait for both threads to finish t1.join(); t2.join(); System.out.println(counter.getCount()); // should output 2000These examples use the java.lang package.