Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
import java.util.concurrent.Semaphore; public class DiningPhilosophers { static Fork[] forks = new Fork[6]; static Philosopher[] philosophers = new Philosopher[6]; public static void main(String[] args) { for(int i = 0; i < 6; i++) { forks[i] = new Fork(); } for(int i = 0; i < 6; i++) { philosophers[i] = new Philosopher("P" + i, forks[i], forks[(i + 1) % 6]); } for(int i = 0; i < 6; i++) { philosophers[i].start(); } for(int i = 0; i < 6; i++) { try { philosophers[i].join(); } catch(InterruptedException e) { } } } static class Fork { Semaphore fork_semaphore = new Semaphore(1); void take_fork() { try { fork_semaphore.acquire(); } catch (InterruptedException e) { } } void put_back_fork() { fork_semaphore.release(); } } static class Philosopher extends Thread { String name; Fork left_fork; Fork right_fork; Philosopher(String _name, Fork _left, Fork _right) { name = _name; left_fork = _left; right_fork = _right; } @Override public void run() { left_fork.take_fork(); right_fork.take_fork(); eat(); left_fork.put_back_fork(); right_fork.put_back_fork(); think(); } void eat() { System.out.println(name + " is eating!"); try { Thread.sleep(100); } catch (InterruptedException e) { } } void think() { System.out.println(name + " is thinking!"); } } } /// 1 2 3 4 5 6
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)